Java Programming Principles

Source: Internet
Author: User
Tags set set

Objective:

The object-oriented language of Java is in fact very consistent with the human life thinking pattern, because it takes object as its object of study, so-called "everything Objects". A man, an apple, an ant are all objects. Therefore, its design principles and design patterns are all around the object of thought condensed out of the idea of the essence, all with time stability. In this section we will focus on the Java design principles and the inside of Java programming principles.

One: The principle of single job

1.1 explanation : Refers to Java in the class design, should let a class only complete a specific thing, assume their own single responsibility. Can only be caused by a single cause of its own changes, that is, its functional uniqueness. The specific properties and methods should be designed around how to accomplish this single function, regardless of other functions.

1.2: Example

Example: If we are now to complete the message to the user, we define this class, then this class will just send mail this action, as to who sent the mail, send the content is what, we can use the mail class to complete processing, this sendmail class does not go to maintain these things

 Public class mail{  private String address;   The address sent is the  private String content;   The content sent is  private person person;   Send to who }
 Public class // Send mail Public     void Send () {
Send mail Detail
}}

Extended meaning :

A class can be understood as a person, society is composed of people, society can be understood as a large container, people are the component. Everyone should make their career single, as far as possible to complete their own tasks, with "focus" of the spirit. Specializing in an industry, hackers and painters have such a phrase: "A person wants to make a contribution in a certain field, must devote oneself all the energy". Let yourself devote oneself to one thing, so that it is possible to achieve certain performance. After all, a person's energy is limited.

Two: dependency inversion principle:

2:1: explanation : High-level components should be dependent on abstraction rather than specificity, that is, the interface programming should be faced. Dependent member variables and parameters should be abstract rather than specific.

Extended meaning: If you map to the real world, you can see that this phenomenon is ubiquitous. For example, in a corporate company, the words of the top leaders are mostly generalized and conceptualized. Do not point to specific things, just generalities. This through the layer of specific division of labor, to each person to complete the specific task, there are the bottom of the characters to complete the specific details

2.2: Example: If an e-commerce website is engaged in a promotion, we need a price observer to observe its price change, this time we'd better define a specific observer and implement the Observer interface, the benefit is to reduce the amount of code, you can reuse the method provided by observer. and maintain a set set, where the specific collection is not used, the member variables are best abstracted, so that when the subclass is implemented, we are free to choose, not write to die. Increase the flexibility of the program, such as the late we need to observe the user to sort, so that you can do treeset in the method of implementation, if it is not necessary for higher performance, you can use HashSet as a concrete implementation:

public class Priceobserver implements Observer {   private set<users> observers;

}

  

Three: The principle of the Richter replacement

3.1 Explanation: Wherever the parent class appears, it can be substituted with subclasses, and the original function has not changed, that is, all references to the base class must be able to use the object of its subclass transparently.

3.2: Example: Here we have to mention the polymorphism of Java, that is, the parent class refers to the subclass object, we define an animal class, it has the function of flying and running, we are implementing a subclass, called Pig, but here is a problem, pig it can not fly (unable to implement the Fly method), how to do?

 Public class animal{   publicvoid  fly ();     Public void   Run ();}  Public class extends animal{    @override    publicvoid  Fly () {    }    @override     publicvoid  run () {    }}

Fix the following: In order for the parent class to be more adaptable and scalable, we should add a parameter to determine whether it will work:

public class animal{public   absract void  Fly (boolean able);   Public absract void  Run (boolean able);

In short, it has the following several we must observe:

    • Subclasses can implement the abstract methods of the parent class, but cannot override the non-abstract methods of the parent class.
    • Subclasses can add their own unique methods.
    • When a subclass overrides or implements a method of the parent class, the method's preconditions (that is, the parameter of the method) are more lenient than the input parameters of the parent class method.
    • When a method of a subclass implements an abstract method of the parent class, the post condition of the method (that is, the return value of the method) is stricter than the parent class.

3.3: Extended meaning : This also should be a sentence: superseding, the former wave died on the beach. The son inherited the mantle of his father, who generally possessed the power of his father. Of course, this sentence is not rigorous, we see a lot of stories, the general father does the occupation, will not let the son continue to do. On the other hand, I would like to understand that it is learning ability. Teachers can be understood as the parent class, students understand as subclasses, subclasses to implement the parent class method, improve their learning ability, through the last learning to have the knowledge and wealth of teachers.

Four: Dimitri Principle

4.1: Explain: A class should be as far as possible to encapsulate themselves, with their friends, the general friend class are member variables and parameters, non-friend class is a local parameter.

4.2: Example: If we are to design a device to open the method package class, it contains a number of details, such as power on, turn on the operating state of the device, turn on the device's screen display, turn on the sound drive, this time we need to encapsulate it as far as possible, exposing the easy-to-use API:

 public  class   Opendevice { private   Mediahelper Mediahelper;  private  void   Openpowersource () {System.out.println ( "Turn on power ..."     public  void  Open () {//          Openpowersource ();    Mediahelper.openmedia (); }}
 Public class // Friend class        Private void Openscreen () {        System.out.println ("open screen");    }         Private void Opensound () {        System.out.println ("open Sound");    }      Public void OpenMedia () {// encapsulates two private methods, increasing its permissions to expose         openscreen () outward;        Opensound ();    }}

In short, it has the following several we must observe:

    • The member variables of this class should be set to private as much as possible, and the external access rights should be reduced.
    • own methods of this class as private as possible, exposing only the business logic of the method, rather than the technical details of the internal method
    • If a friend class has an indirect reference, it should hide the indirect reference and not expose it from the middle. We can add an intermediate class to manage all the required classes

extended meaning : A person should try to perfect themselves, as far as possible with their friends, do not transition to rely on others, should ensure their independence, or refuse to deal with outside strangers. This is a "security" policy, and it is possible to have a certain risk of implementing an external connection. Just like some of the children's nature pure, by some socially dubious people with misguided (than my cousin). Of course not understood as the closure of the heart, refused to communicate with the outside. This will only live in a narrow area, not to see the outside scenery, will make their own vision narrowed and short. thus shortsighted. One of the features in software design is: cohesion, low coupling. One should try to be as perfect as possible and to minimize contact with others. There is a saying called "If you are blooming, butterfly is in the way". The bloom here can be understood as "cohesive". Let your ability gather to bloom the most beautiful self.

V: Interface Isolation principle

Explanation: An interface as much as possible function single, do not assume too much responsibility.

Example: Here you can use spring's beanfactory class to illustrate the problem:

The beanfactory is the root interface of the Spring Bean container. Provides an API that gets the bean, whether it contains beans, whether Singleton and prototype, gets the bean type, and the Bean alias. Its core function lies in the management of the bean.

Autowirecapablebeanfactory add integration with other framework features. If you have integrated webwork, you can use spring to manage actions, and so on. Mainly used for other places references Beanfactory

Hierarchicalbeanfactory provides access to the parent container, with the primary function being the parent container's operation

Configurablebeanfactory, which provides factory configuration functions, is primarily responsible for configuring beans

The Configurablelistablebeanfactory synthesizer provides parsing, modifying bean definitions, and initializing the singleton.

Listablebeanfactory provides an enumeration of bean instances within a container. This side does not consider instances within the parent container.

You can see that the beanfactory down interface has its own responsibilities, dividing the specific functions and responsibilities, each independently, each interface to complete its own tasks.

The following principles should be observed:

    • The interface is as small as possible, but there are limits. The refinement of the interface can improve the design flexibility, but if it is too small, it will cause too many interfaces, making it too complex, so be sure to moderate.
    • Customizing the service for an interface-dependent class exposes only the methods it needs to the calling class, and the methods it does not need are hidden. A minimal dependency can be established only by focusing on providing a customized service for a module.
    • Improve cohesion, reduce external interaction, and in a limited range to make the interface with the least way to accomplish the most things.

Extended meaning : This is actually the same as the role of a single second. But one is talking about classes, and one is talking about interfaces. Interfaces and classes are two different concepts, one is a physical thing, the other is abstract function generalization. Here I would like to talk more about the issue of responsibility, and I am talking about occupation in class. Responsibility should be specific to specialize in one aspect, not too many things, the above mentioned that we have limited energy, the specific responsibilities are limited, should be as far as possible to bear less, so as to better complete the current work. Unless you have extra energy, you can explore all kinds of things.

Six: The principle of opening and shutting

Java: Open to extensions, closed for modifications. For a system, there should be a good set of extensibility to facilitate the expansion of functionality, without affecting the specific other components. Everything has to be in the bud. When the expansion of the function, try not to modify the original code, do not change the original things.

In short, it requires us to make the following:

1: Through the interface or abstract class constraints extension, the extension is bounded, not allowed to appear in the interface or abstract class does not exist in the public method;

2: Parameter types, reference objects use interfaces or abstract classes as much as possible, rather than implementing classes;

3: The abstraction layer is kept as stable as possible, and modifications are not allowed once determined.

extended meaning : What I learned from this is that when communicating with a person should do is not at random criticize a person, do not try to change a person, I do not have so much power, and not so much ability to point to other people's life. Try not to modify, if you want to be on the basis of other aspects of the expansion. such as the extension of interest, the development of the new continent. After all, everyone is not a fool, everyone has their own living space, do not modify the unauthorized. On the other hand, a person should constantly expand their abilities.

Summarize

This post mainly introduces the six principles of Java program design, remembering that a core idea of software design is: high cohesion, low coupling . No matter what the means and measures, we are in the direction of these two goals. In the process of routine development, we should strictly follow these design principles, so that the design process is more reusable and robust features, but also for our program development more guidance.

Java Programming Principles

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.