Java design patterns - six principles

1, single-function principle (Single Responsibility Principle, SRP)

definition

There should never be more than one reason for a class to change.

There should be one and only one cause of change class

In other words, that is an interface or class has only one duty

benefit

  • Reduced complexity class, achieve what responsibilities are clear and unambiguous definitions;
  • Improve readability, reduce complexity, improve readability of course;
  • Improve maintainability, improve readability, it is certainly easier maintained;
  • Risk reduction due to the change, when necessary change, if a single interface functions well, only one interface to modify the corresponding implementation class impact, no impact on other interfaces, this scalability of the system, maintenance We have a very big help.

Best Practices

Division of duties is difficult to design more difficult, in order to fully comply with the single responsibility, the principle is the interface there must be a single responsibility, as far as possible the design of the class is only one cause of change

2, Richter substitution principle (LiskovSubstitution Principle, LSP)

Advantages and Disadvantages of inheritance

  • advantage
    • Code-sharing, reduce the workload of the class is created, each subclass has methods and properties of the parent class;
    • Improving code reuse;
    • Subclasses can parent shape, but different from the parent;
    • Scalability code, the parent class implementation will be "do whatever" a;
    • Improve the openness of the product or project.
  • Shortcoming
    • Inheritance is invasive. As long as inheritance, you must have all the attributes and methods of the parent class;
    • Reduce the flexibility of the code. World subclass must have attributes and methods of the parent class, make a subclass of freedom have become more constrained;
    • Enhanced coupling. When the constants, variables and methods of the parent class is modified, we need to consider amending the subclass, and in the absence of standardized environment, this change may bring very bad results - large chunks of code refactoring.

definition

If for each object o1 of type S there is an object o2 oftype T such that for all programs P defined in terms of T,the behavior of P is unchanged when o1 issubstituted for o2 then S is a subtype of T.

If each type of objects o1 S, O2 has an object of type T, and T is defined such that all of the program when all the objects P o1 are replaced by substituting o2, the behavior of the program P has not changed, then the type S is a subtype of type T.

These are the LSP "most authentic" is defined, but may not be easy to understand, it also has another relatively clear definition:

Functions that use pointers or references to base classes must be able to useobjects of derived classes without knowing it.

All references to the local base class can be used transparently object whose subclasses.

Popular speak, as long as the parent class where the subclass that can occur can occur, and replaced subclass does not produce any errors or exceptions, the user may simply need to know is the parent class or subclass. However, not vice versa, where there appears subclass, the parent may not be able to adapt. (LSP can be positive but not significant with the opposite of use)

specification

Richter substitution principle for the good inheritance defines a specification, a simple definition contains 4 layer of meaning:

  • The subclass must fully implement the method of the parent class

    Subclasses can not complete implementation of the method of the parent class, or some method of the parent class of "distortion" has occurred in the subclass, it is recommended to disconnect the parent-child inheritance, use-dependent, aggregation, or the like instead inheritance relationship composition.

  • Subclasses can have their own personality

  • Input parameters covering or method of implementation of the parent class may be amplified ** (cover not overloaded) **

  • Output or override the parent class implementation results may be reduced

    A return value of the method of the parent class is a type T, the same subclass (heavy duty or override) the return value of S, then the principles Richter requires replacement must be less than equal to T S, that is, either S and T are the same type, or is a subclass of T S.

Best Practices

In the project, when using the Richter substitution principle, try to avoid a subclass of "personality", once a subclass of "personality", the relationship between this subclass and superclass is difficult to reconcile, handle class as the parent class use a subclass of "personality" is denied - pity points; handle used as a separate class of business, the coupling relationship between the code will become complicated and confusing - the lack of an alternative class standard.

3. Dependency Inversion Principle (Dependence Inversion Principle, DIP)

definition

High level modules should not depend upon low level modules.Both should depend uponabstractions.Abstractions should not depend upon details.Details should depend upon abstractions.

  • High-level modules should not depend on low-level modules, both of which should rely on its abstract;
  • Abstract should not rely on the details;
  • Details should depend on the abstract.

Dependency Inversion principle embodied in Java:

  • Abstract dependencies between modules occurs, no direct dependencies between classes, which dependency is generated by the interface or abstract class;
  • Interface or abstract class does not depend on the implementation class;
  • Implementation class dependent interface or abstract class.

More streamlined definition is " for interface programming ."

Three dependent wording

  • Passing the object constructor dependency (constructor injection), in a class object via a constructor dependency declarations
  • Setter method passes dependent objects (Setter dependency injection), a method is provided Setter abstraction declared dependencies
  • In the method of dependent objects declared in the interface (interface injection)

Best Practices

Dependency Inversion principle is the essence of each class by the abstract (interface or abstract class) or implement the module independently of one another, do not affect each other to achieve loose coupling between modules, how we use this rule in the project do? As long as you follow a few rules can:

  • Each class has a possible interface or abstract class, or both abstract classes and interfaces are provided

    This is the Dependency Inversion of the basic requirements, interfaces and abstract classes belong to the abstract, it may have abstract Dependency Inversion

  • Type variable as far as possible the surface of the interface is an abstract class or

  • Any class should not derive from specific classes

  • Try not to override the base class methods

  • Use the principle of combined Richter replaced

    Local subclass the parent class appears able to appear, and then DIP, we can come to a common rule: the interface is responsible for defining public properties and methods, and declare dependencies on other objects, abstract class is responsible for implementing structural part of the public, accurate implementation class business logic, while refinement of the parent class at the appropriate time.

Dependency Inversion principle is the principle of six design principles of the most difficult to achieve, it is an important way to realize the principle of opening and closing, Dependency Inversion Principle is not achieved, they could not realize open to extension but closed for modification. In the project, as long as you remember that it is "programming to an interface" basically captures the core principle of dependency inversion.

4, the interface segregation principle (Interface Segregations Principle, ISP)

definition

Interface Segregation Principle There are two definitions:

Clients should not be forced to depend upon interfaces that they don't use.

The client should not rely on it does not require interfaces.

Explanation: The client interface is what is required to provide any interface to weed out unwanted interfaces, the interface would need to be refined to ensure its purity;

The dependency of one class to another one should depend on the smallest possible interface.

Dependencies between classes should be based on a minimum of interfaces.

Explanation: The minimum requirement is that the interface, the interface is required to refine the interface pure, exactly the same with the first definition, but a description of two different things.

Summary: the establishment of a single interface, do not create bloated interface. Then plainly say: try to refine the interface, while the interface methods as little as possible.

Interface Segregation principle of single responsibility principle VS

  • Interface isolation single responsibility principle and new perspective is not the same

  • Single Responsibility required classes and interfaces of a single responsibility, focusing on the role, which is divided on the business logic;

  • The method of claim Interface interface segregation principle as little as possible.

For example a duty interface 10 may comprise a method, this method are placed in a 10 interface, and access to a plurality of modules, each module in accordance with the authority to access, through the document constraint "approach is not used outside the system Do not access, "according to the principle of single responsibility is allowed, according to the interface segregation principle is not allowed, because it requires" to make use of more specialized interfaces. " What special interface refers to? Refers to each module should be a single interface, to provide several modules should have several interfaces, rather than creating a huge bloated interface to accommodate all client access.

// TODO still feel not too bad ...

specification

  • Interface to be as small as possible

    • There's a limit
    • We can not go against the principle of single responsibility (division of the business)
  • Interface to high cohesion

    High cohesion principle is specific to the interface isolation, requiring as little as possible in the interface methods public announcement, the interface is external commitments, the less the more favorable development of the system, the less risk of change commitments, but also help to reduce costs .

  • Custom service (method only provides visitors needed)

    For example: a user interface for the query, the query should provide specific user ID or the user name service query associated with a particular interface is equal to, rather than providing a query interface with Map (or similar Mybatis Example) parameter

  • Interface design is limited

    • The smaller the particle size of the design of the interface, the more flexible system;
    • However, it also brings flexible complicated structure, increasing the difficulty of development, reduce maintainability, this is not a project or product expect to see;
    • So the interface design must pay attention to moderate, the "degree" of how to judge it? Based on experience and common sense, is not a standard curing or measurable.

Best Practices

Interface segregation principle is the definition of the interface, but also the definition of classes, interfaces and classes make use of atom or atomic class interfaces assembled. However, this division is how to design atomic model of a major problem, it can be measured according to the following rules in practice:

  • Only an interface to a service or business logic submodule;
  • public interface methods by compressing the business logic, interfaces often to look back, try to make the interface to achieve "bones covered with flesh," rather than "plump" in a bunch of ways;
  • Interface has been polluted, try to modify, change, if greater risk, the use of the adapter mode conversion process;
  • Understanding of the environment, refused to follow blindly. Each project has a specific product or environmental factors, different environments, split the standard interface is different. In-depth understanding of the business logic, interface design combined with the actual situation.

5, Demeter (Law of Demeter, LoD)

Also known as the least knowledge of the principles (Least KnowledgePrinciple, LKP)

definition

An object must have a minimum understanding of other objects

More simply, a class should know the least they need to be coupled or call the class, how you internal (coupled or call the class) is complex and I are okay, that is your thing, I know you provided so many public methods, I would call so much, the other not and will not care about me.

meaning

  • Only communicate with friends

    Demeter is also an English explanation:

    Only talk to your immediate friends.

    Only direct communication with friends.

    A class and communicate with friends only, with no strange kind exchange, do not appear getA (). GetB (). GetC (). GetD () case (allowed such access in an extreme situation, that is, each after the dot same return type), the relationship between the classes and class is established between the classes, methods, rather than between, so far as possible without introducing a method of a class object does not exist, of course, JDK API classes provided except.

  • There is also the distance between friends

    Demeter requirements of class "shy" a little, try not announced too many public methods of public and non-static variables, restrained as much as possible, more use of private, package-private, protected, etc. access.

  • It is their own

    Such an approach would appear frequently in practical applications: in this category may also, on the other classes are not wrong, then how to measure it? You can adhere to such a principle: If a method in this class, neither increased relations between classes, but also does not adversely affect the class, it is placed in this category.

  • Use caution Serializable

Best Practices

  • The core concept of the Law of Demeter is the decoupling between classes, weak coupling, after only weakly coupled, like reuse rate can be improved. The results of its request that generated a lot of transit or jump type, resulting in increased complexity of the system, but also for the maintenance of a difficulty. We need to weigh when using the Law of Demeter, not only did it make clear structure and cohesion and low coupling to achieve high inside.

  • Demeter claim decoupling between classes, but the decoupling is limited, unless it is the smallest unit of the computer - binary 0 and 1. That is completely decoupled, in the actual project, it is necessary to consider the appropriate principles, not to apply the principle to do the project. Principles just for reference, if contrary to this principle, the project is not likely to fail, which we need to repeatedly measure when using the principle to follow is not wrong, strict implementation is "too far."

6, the opening and closing principle (Open Closed Principle, OCP)

The principle of opening and closing the Java world, the most basic design principles, which guide us in how to build a stable, flexible system

definition

Software entities like classes,modules and functions should be open for extension but closed formodifications.

A software entity, such as classes, modules and functions should be open for extension but closed for modification.

In other words, a software entity should be achieved by extending the change, rather than to achieve change by modifying existing code.

importance

Opening and closing principle is a basic principle of most of the five principles described in the previous sections are open and closed forms specific principles, that is to say the first five principles that guide the design of tools and methods, and opening and closing its principle is the spiritual leader . From a different angle to understand, in accordance with the title of the Java language, opening and closing principle is an abstract class, the other five principles is a specific category, opening and closing the principle position in the field of object-oriented design is similar to the Newton's first law of mechanics, hook Law of shares in geometry, the status of mass-energy equation in special relativity, its status and no one can.

How to use the principle of opening and closing

  • Abstract constraints

    • Interface or abstract class constraints by extension, the extended boundary is defined, the method does not exist in the public interface or abstract class is not allowed;
    • Parameter type, make use of the referenced object interface or an abstract class, not the implementation class;
    • Abstraction layer as stable as possible, i.e. can not be modified once it is determined.
  • Metadata (Metadata) behavior of the control module

    What is metadata? Is used to describe data and environmental data, configuration parameters layman's terms, the parameters can be obtained from the file, it can be obtained from the database.

  • Develop Project Charter (team agreed)

  • Change package

    • The same change package to an interface or abstract class;
    • The different variations of the package to a different interface or abstract class, should not have two different variations appear in the same abstract class or an interface.
    • Change package, which is subject to change protected (protected variations), is expected to find there is a change or an unstable point, we create a stable interface points for these changes, to be exact change package that may occur, or once predicted " Sixth Sense "found to have a change, it can be packaged, design patterns 23 are encapsulated to change from different angles

Best Practices

  • Opening and closing principle is only a principle

    Open Closed Principle just spiritual slogans, methods to achieve embrace change very much, is not limited to these six design principles, but follow this six design principles basically deal with most of the changes. Therefore, we should as far as possible in the project six major principles, the right time can be extended, for example, can solve some flaws in the system by way of replacement class file. Everyone in the development of the more commonly used method for repairing defects is to replace the class, such as a software product has been in operation, found a flaw, need to fix how to do? If you have automatic update feature, you can download a .class file directly overwrite the original class, restart the application (does not necessarily have to restart) can solve the problem, that is, through alternative class files fixes a flaw, of course, this approach can also be applied to the project, the running of the project found the need to add a new feature, by modifying the original implementation class can solve this problem, provided that: class must achieve high cohesion and low coupling, otherwise replace the class file can cause unexpected failures.

  • The project is very important regulations

    If you are a project manager or architect, we should try to make their own stable of project members, in order to establish a highly efficient team culture stabilized, the charter is a common knowledge that all team members crystallization, but for all members must comply with the agreement. Excellent charter can bring the project to bring a lot of benefits, such as increased development efficiency, lower defect rates, improve team morale, improve the technical level of the members, and so on.

  • Predict change

    In practice the process, architect or project manager once found may change or changes have occurred, you will need to consider whether the existing infrastructure can easily implement this change. Architect to design a system not only to meet current needs, but also to adapt to changes that may occur, this is a good architecture.

Opening and closing principle is an ultimate goal, anyone, including masters can not do one hundred percent, but efforts in this direction, can very significantly improve the architecture of a system of truly "embrace change."

7. Conclusions

First, neither the six design principles still 23 design patterns, in fact, a fundamental objective " embrace change ", including changes in demand, changes in the operating environment, enhance performance requirements, etc., to achieve a demand is not difficult, but when change comes, whether equanimity, that is a technical live.

Secondly, the "embrace change" level is the implementation of the code to what? - *** your code is maintainable, scalable ***, or should I say "pull launched a whole", little changes a lot of things have to follow to change.

Again, in order to "embrace change" so that your code is easy to maintain and extend the core concept *** "high cohesion, low coupling" *** and "*** oriented programming interface (abstract-oriented programming ) *** "

Finally, design principles, design patterns are senior summary of "experience", but not "terms", as far as possible to follow these norms will make your design as close to perfect, but in this world there is no perfect thing, everything should have a degree, do not identify dead science, not in order to "set mode" and application design patterns, to analyze specific issues, to weigh the actual situation.

Do another beautiful design, code, and then write the perfect project to do and then meet the criteria, once the project is at a loss, larger than the output product into that whole is nonsense!

References: "Zen Design Patterns"

Reproduced in: https: //juejin.im/post/5cfd2944f265da1bb003b249

Guess you like

Origin blog.csdn.net/weixin_33816300/article/details/91459953