Design Pattern Zen Design Principle Concept Summary _ design pattern

Source: Internet
Author: User
Conceptual summary of Design principles

Read the design patterns of Zen, the design principles to do a summary of the concept, if you want to better understand, or to see the specific details, this side can only be a rough summary, as a learning note. Principle of single responsibility

English Name: Single Responsibility principle abbreviation SRP

English definition:

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

There should be and only one reason for the change of class.

Advantages: 1. The complexity of the class is reduced and there is a clear definition of what responsibilities to achieve; 2. Readability increased (complexity reduced, readability naturally increased); 3. Maintainability Improvement (readability is improved, maintainability is naturally easier); 4. Risk reduction due to change

Summary: For the single responsibility principle, the interface must achieve a single responsibility, class design as far as possible to achieve only one reason to change

PS: A single responsibility principle proposes a standard for programming, using "responsibility" or "cause of change" to measure the quality of interfaces or classes or methods, but "responsibility" and "reason for change" are not measurable, because of the project, because of the environment and the principle of replacing the Richter

English name: Liskov substitution principle

Basic Review

The benefits of inheritance 1. Code sharing, reducing the amount of work to create a class, each owning a method and attribute of the parent class; 2. Improve the reusability of the Code; 3. Subclasses can resemble the parent class, but also different from the parent class, have their own methods and attributes; 4. Improve the scalability of the Code, the implementation of the parent class can "do whatever"; 5. Improve the openness of a product or project

Disadvantages of inheritance 1. Inheritance is intrusive, and as long as it inherits, it must have all the properties and Method 2 of the parent class. Reduce the flexibility of the code. Subclasses must have properties and methods of the parent class, allowing the subclass to be more constrained in a free world; 3. Enhanced coupling, when the parent class constants, variables and methods are modified, you need to consider the modification of subclasses;

Richter replaces two definitions: 1. If the object of each type S is O1, there is an object O2 of type T, so that all program P defined by T is substituted for O2 when all the objects O1 are replaced by the action of the program p, then the type S is the subtype of the type T. 2. All references to base classes can transparently use objects of their subclasses.

Meaning

1: Subclasses must fully implement the method of the parent class (this refers to the parent class is generally an interface or abstract class);

Note 1 when calling other classes in a class, be sure to use the parent class or interface (so that many subclasses can pass in 2 of the methods that the parent class is a parameter to). If a subclass cannot fully implement the method of the parent class, or if some methods of the parent class have been "distorted" in the subclass, it is recommended that you disconnect the parent-child inheritance relationship, take dependencies, aggregate, A combination of such relationships instead of inheritance.

2. Subclasses can have their own personality;

Note: Upward transition is safe, downward transition (downcast) is unsafe, from the Richter replacement principle, there are subclasses of the local parent may not appear

3. Input parameters can be magnified when overriding or implementing methods of the parent class;

When a subclass's method input parameter is magnified, the relationship between the subclass and the parent class is overloaded (the method name is the same and the input parameters are different). If the input parameters of the subclass are shrunk. That is, the subclass's input parameter is a subclass of the input parameter of the parent class, and the subclass's method is executed without overriding the method of the parent class, which can cause confusion in the business logic. In other words, if you want to execute a method of a subclass that has the same name as the parent class method, you must override the method of the parent class.

4. The output can be reduced when the parent class method is overridden or implemented

In the case of a overwrite, the input parameters of the same method are the same for the parent class and the subclass. The return value type of a subclass method should be less than or equal to the return value type of the parent class, that is, the return value type of the parent class should equal the return value type of the subclass, or the return value type of the parent class is the parent class of the return value type of the subclass.

Summarize
The purpose of using the Richter substitution principle is to enhance the robustness of the program, version upgrade can also maintain good compatibility, even if the addition of subclasses, the original subclass can continue to run, in the actual project, each subclass corresponding to the different business meaning, using the parent class as a parameter, passing different subclasses to complete different business logic. Try to avoid the "personality" dependency inversion principle of subclasses

English name: dependence inversion principle

What is dependency inversion:

Let's talk about dependence, dependency is the dependency between classes is the real implementation of the dependencies between the classes, that is, implementation-oriented programming, and writing programs need to abstract the real things, the abstract interface with the interface and abstract class, and then according to the needs of the system design to produce abstract dependencies, Instead of relying on things in traditional thinking, this is upside down.

Meaning: 1. High-level modules should not rely on low-level modules, both of which should rely on their abstraction; 2. Abstractions should not rely on details; 3. Details should be dependent on abstraction;

The corresponding Java performance is 1. The dependencies between modules occur through abstraction, and there is no direct dependency between classes, and their dependencies are generated by interfaces or abstract classes; 2. Interface or abstract classes are not dependent on the implementation class; 3. Implement class dependency interface or abstract class;

The more quintessential definition is "interface-oriented programming."

For example: The driver drives, the car is an interface, the function of the car is run, the interface has run method, all cars must inherit this interface, the driver's method of driving the incoming parameter is also necessarily an example of interface;

Advantages

The dependency inversion principle can reduce the coupling between classes, improve the stability of the system, reduce the risk caused by parallel development, and improve the readability and maintainability of the code.

Note: In Java, as long as you define a variable there must be a type, a variable can have two types: surface type and the actual type, the surface type is defined at the time of the type given, the actual type is the type of object, such as
Idriver Zhangsan = new Driver (); Surface type is idriver, the actual type is Driver, I understand here: compile-time is the Idriver type, Zhangsan can call the method can only be the way of the Idriver, But the Run-time type is driver, and the actual invocation is the method of implementing the class. It is safe to use the upward transition.

Three ways to rely
Dependencies are transitive, a objects depend on B objects, B objects depend on C objects, C objects depend on D, just keep in mind the key point: As long as you are abstract dependent, there is nothing to fear, even with multiple layers of dependency transfer.

1. Construction method passing dependent objects (constructor injection)

Public interface Idriver {
    //The driver should be able to drive the car public
    Void Drive ();
}
public class Driver implements idriver{
    private ICar car;
    constructor injection to public
    Driver (ICar _car) {
        this.car = _car;
    }
    The driver's main duty is to drive the car public
    Void Drive () {
        this.car.run ();
    }

The 2.Setter method passes the dependent object (set Setter method declaration dependency in abstraction, this is setter dependency injection)

Public interface Idriver {
    //vehicle model public
    void Setcar (ICar car);
    Drivers should be able to drive cars public
    void Drive ();
}
public class Driver implements idriver{
    private ICar car;
    public void Setcar (ICar car) {this
    . car = car;
    }
    The driver's main duty is to drive the car public
    Void Drive () {
    this.car.run ();
    }

3. Interface Declaration Dependency object (Declaration of dependent object in interface method;)

Public interface Idriver {
    //is the driver should be able to drive the vehicle public
    Void Drive (ICar car);
}

Summarize

The essence of the dependency inversion principle is to make the implementations of each class or module independent of each other through abstraction (interfaces or abstract classes). Do not interact with each other to achieve loose coupling between modules, the rules we use in the project are as follows: 1. Each class has interfaces or abstract classes as much as possible, or both abstract classes and interfaces. (with abstractions to rely on inversion); 2. The surface type of the variable makes the interface or abstract class as much as possible; 3. Any class should not derive from a concrete class; 4. Try not to duplicate the method of the base class; 5. Combined with the Richter replacement principle;

Combined with the Richter substitution principle: The parent class appears where the subclass can appear;

In conjunction with this chapter comes the popular rule: the interface is responsible for defining the public properties and methods, and declaring dependencies with other objects, the abstract class is responsible for the implementation of the common construction method, the implementation class is responsible for the accurate implementation of business logic, and at the appropriate time to the parent class refinement.

PS: The advantages of the dependency inversion principle is difficult to embody in small projects, such as projects less than 10 months, using a simple SSH architecture, basically not too much effort can be done, whether the use of dependency inversion principle has little impact. However, in a large and medium-sized project, the use of dependency inversion principle has a lot of advantages, especially to avoid some of the problems caused by non technical factors. The larger the project, the greater the probability of the change in requirements, and the constraint on the implementation class by using an interface or abstract class designed with the dependency inversion principle to reduce the increase in the amount of work caused by the change in demand. Personnel changes in large and medium-sized projects are also frequent, if the design is good, the code structure is clear, the impact of personnel changes on the project is basically zero. The maintenance cycle of medium and large projects is generally very long, and the dependency inversion principle allows maintenance staff to scale and maintain easily. Interface Isolation principle

English name: Interface segregation principle

Meaning:

Clients should not is forced to depend upon interfaces that they don. (Clients should not rely on interfaces he does not need)

The dependency of one class to another one should depend on the smallest possible. (Dependencies between classes should be based on the smallest interface)

Establish a single interface, do not create bloated and bulky interfaces; the principle of changing a bloated interface to multiple independent interfaces is the interface isolation principle, which is a contract that we provide externally at design time, and can be used to prevent the spread of future changes by defining multiple interfaces, providing flexibility and maintainability of the system.

The difference between the principle of interface isolation and the principle of single responsibility:

The principle of single responsibility requires a single function of class and interface, focusing on responsibility and division of business logic;

The interface isolation principle is to require the interface to be as few as possible;

The principle of interface isolation is to standardize the interface, it includes the following 4 meanings: 1. Interface should be as small as possible; interface isolation principle when the interface is split, the single responsibility principle must first be met; 2. Interface to be high cohesion, require the interface to publish the public method as little as possible, interface when external commitments, Less commitment to the development of the system more favorable, the less risk of change, but also conducive to reducing costs; 3. Develop services and provide excellent service to individual individuals 4. Interface design is limited;

The practice of measuring the Rule 1. An interface serves only one child module or business logic; 2. The public method in the interface is compressed through the business logic; 3. The contaminated interface, as far as possible to modify, if the risk of change is greater, the use of adapter mode for conversion processing; 4. Understanding the environment, refusing to follow blindly; Dimitri Law

English: Law of Demeter also known as the minimum knowledge principle (least knowledge principle)

Defined:

An object should have a minimal understanding of other objects; 1. Only communicate with friends (avoid the exchange with unfamiliar classes, reduce system coupling, improve system robustness) 2. There is a distance between friends; (the coupling is low, minimizing the public method and public properties) 3. It's your own. (If a method is placed in this class, that is, without increasing the relationship between the classes and not negatively affecting the class, place it in this class); 4. Use serializable carefully;

Summarize

The core concept of Dimitri law is decoupling between classes, weak coupling, only weak coupling, the reuse rate of class can be improved, the result of which is to produce a large number of relays or jump classes, resulting in the complexity of the system upgrade, colleagues also brought difficulty for maintenance. In the use of Dimitri rules need to be weighed repeatedly, not only to make the structure clear, but also to achieve high cohesion low coupling; closing principle

English name: Open Closed principle

Meaning: Software entities like Classes,and functions should is open for extension but closed for modifications

A software entity such as a class. Modules and functions should be open to extensions and closed for modification.

Attention
Opening and closing principle is open to expand, to modify the closure, does not mean that do not make changes, the underlying module changes, it is necessary to more high-level modules to be coupled, otherwise it is a helpless code fragment.

The importance of the opening and closing Principle 1. The effect of open and closed principles on testing. (The original test still has no effect, because we used the extension to implement the business logic changes) 2. The principle of opening and closing can improve the reusability; 3. The principle of opening and closing can improve maintenance; 4. Object-oriented development requirements (the redesign of the time to take into account the possible changes in factors, and then leave the interface, waiting for "may" become "reality");

How to use the opening and closing principle 1. Abstract constraint 2. Metadata (metadata) control module behavior. (metadata is a popular way to configure parameters, parameters can be obtained by file or from the database, 3. Formulation of the Project Charter 4. Package changes (1. The same changes are encapsulated into an interface and abstract class; 2. Encapsulate different changes into different interfaces or abstract classes, There should not be two different changes appearing in the same interface and abstract class.

PS: The opening and closing principle is an ultimate goal, anyone, including the masters of the people can not be fully achieved, but in this direction, can be very significant to improve the structure of a system, truly "embrace change"

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.