The solid principle of design pattern and look back

Source: Internet
Author: User

Undergraduate stage to learn design patterns, at that time on the design model of the Five Principles of--solid principle of the concept and understanding is still relatively vague, at this time passed 2 years, in the study of "Advanced software Engineering" course, the teacher also mentioned the design pattern, the course also discussed in detail the five principles of the process, This solid principle again back to the author put forward some more popular understanding of it ~

I. What is design mode?     So what is design mode?
    Design pattern is a design scheme which can solve a kind of software problem and can be reused in the broad sense.
    The narrow-sense design pattern is a description of the classes and objects that are used to solve general design problems in a given scenario, and is a solution to the reusable software design problem described in the hierarchy of classes and objects.
    mode embodies the whole idea of the program, Also appears in the analysis or summary design phase, includes the creation pattern, the structural pattern, and the behavioral pattern.
    The four basic elements of the     model include:
    1. Schema name (pattern names)
    2. Problem (Problem): describes when patterns should be used, explains design problems and the causes and consequences of problems, and may also describe the prerequisites that a pattern must meet
    3. Solution (Solution): describes the composition, interrelationships, and respective responsibilities and collaboration of the design. The pattern is like a template that can be applied to a variety of situations, So the solution does not describe a specific design or implementation, but rather provides an abstract description of the design problem and a combination of elements (classes and objects) that are used to solve the problem.
    4. Effects (Consequences): describes the application effects of the pattern and the issues that should be weighed against the usage pattern.
    Where design mode
The solid principle (principles) is as follows:
Single Duty principle (Responsibility)
Opening and closing principle (Open Closed)
The principle of substitution on the Richter scale (Liskov Substitution)
Interface Isolation original principle (Interface segregation)
Dependency inversion principle (Dependency inversion)
Design pattern is the realization of the above principles, so as to achieve code reuse, increase the maintainability of the purpose.

two. Single Responsibility principle

    single Responsibility PRINCIPLE,SRP Thought: For a class, there should be only one cause for it to change (a class has only one duty); Each cause of a class change is a duty, and when the class has multiple responsibilities, it should separate the redundant responsibilities and create classes to complete.
        For example modem can link dial (dial-up connection) \hangup (hang up dialing) and send (send data) \RECV (receive data).
        interface Modem {
        and nbsp   public void dial (String pno);
            public void hangup ();
            public void Send (char c);
            public char recv ();
       }
    modem class has two responsibilities, link management and data communication, which should be separated. There can be more than one method in a class, but a class is only doing one thing.

As far as I'm concerned, I like to add a variety of features to a class in many projects, and C # Forms applications add a variety of code to the form class, and when the requirements change, the form class is always changed, the code gets longer, the maintenance is cumbersome and the flexibility is low.
As the big talk design model says, "If a class takes on too much responsibility, it is tantamount to coupling these responsibilities, and a change in responsibility may weaken or inhibit the ability of this class to perform other duties." This coupling can lead to fragile designs that can suffer unexpected damage when changes occur. " And there are so many things to do in the software design process that it's difficult to find responsibilities and separate those responsibilities from each other.
Example Understanding:
For example, C#winform design Tetris game, you need to change the interface (block drawing \ Erase) and game logic (block drop \ rotation \ Collision \ Mobile, etc.) separation, at least should say the program is divided into two classes-game logic class and WinForm form interface class. When you need to change the interface, Just modify the form class, regardless of the game logic, and the game logic is not very easy to change, separate them to facilitate the modification of the interface, so as to achieve the purpose of code reuse.
in the programming process, we need to think more about the separation of duties in the class, to do a single duty, so that your code is really easy to maintain, easy to expand, easy to reuse, flexible and diverse.

three. Opening and closing principle

Open Closed (openPRINCIPLE,OCP) Idea: The function extension is opened (adding new features), but the modification of the original function code is turned off. When expanding (classes \ modules \ functions can be extended), There is no need to modify the original program, that is, something has not changed, you can add new features.
   
it has the advantage of being flexible and available , can add new features, new modules to meet the changing needs of the new, because the software does not modify the original module, do not worry about the stability of the software. The main principles are:
    1. Abstract principles
    Abstracts all possible behaviors of the system into a bottom layer, since multiple concrete classes can be exported from the abstraction layer to change the behavior of the system, so the design of the variable part of the system is open to the extension.
    2. The principle of denatured packaging
Evaluate and classify all parts of the system that may have changed, each of which is individually encapsulated.
   as the big talk design model says: "When we do any system, there will be a certain change in demand, then how to face the change in demand, the design software can be relatively easy to modify, rather than the whole project to re-start." The opening and closing principle allows the design to remain relatively stable in response to changes in demand. This allows the system to continuously launch new versions after the first version. "
However, no matter how the module is packaged, there are some changes that cannot be encapsulated, and since it is not possible to fully encapsulate, the designer must choose which change package the module should be designed for, and he needs to guess the type of change that is most likely to occur. The abstraction is then constructed to isolate those changes. Often, when small changes occur, the designer will try to cope with the possibility of a larger change, that is, to act immediately when the change occurs. Create abstractions to isolate changes that occur when they occur.
    Example Understanding: (from << design mode >>)
The "one country, two systems" system in Hong Kong is the representative example of the open and closed principle, and the socialist system cannot be changed, but it can be added to the Republic. Another example of a calculator, the original client only addition operation, now need to add new function subtraction, At this point, if you go to modify the original class will violate the "open-closed principle", and when adding a lot of new operations, such code is difficult to maintain.
At this point you need to refactor the program, add an abstract class of operation class, through inheritance or polymorphism, such as isolation of specific addition, subtraction and client coupling, in the face of changes in demand, the program changes by adding new code, rather than changing the existing code, this is the essence of the closed-closed principle.


PS: Think of the previous image processing software, each learning chapter of the new processing like grayscale, enhancement, sampling, binary, etc., on the original basis to continuously add new function implementation, and the last. cpp file more than 4,000 lines, can not look straight Ah! Maybe I actually do a few reasons for the project, to get a project how to plan, the understanding of the design is still not enough, and so on after a few years of work I come back to write some practical experience of the design ideas article, wait and see ~
Remember: The open and close principle is the core of object-oriented design, which brings the great benefits claimed by object-oriented technology, is maintainable, extensible, ready to take, and flexible, and the developer abstracts those parts of the program that show frequent changes, However, it is also not a good idea to deliberately abstract every part of the application, rejecting the immature abstraction and abstraction itself as important.

four. The Richter replacement principle

Richter Substitution principle (Liskov Substitution principle,lsp) thought: Inheritance must ensure that the properties owned by the parent class still hold in the subclass, and that when an instance of a subclass can replace any instance of its parent class, There is a is-a-kind-of-a relationship between them. Only when a subclass (a derived class) can replace its parent (the base class) and the software functionality is not affected, the base class can be reused, and derived classes can add new behavior on top of the base class.
Its essence is that the objects in the same inheritance system should have common behavioral characteristics.
In other words, if a software entity is using a parent class, then it must apply to its subclasses, and the difference between the parent and subclass objects is not perceptible, the parent class is replaced with its subclasses in the software, the behavior of the program is unchanged, and the subclasses must be able to replace their parent type.
Example Understanding:
The parent class is the cat, the subclass has the black cat and the White cat, if one method makes uses in the cat to catch the mouse, then must use the Hu Heica and the White Cat. Again such as << big talk design pattern >> question "is the Penguin a bird?"
Biology: Penguins belong to birds
LSP principle: Penguins do not belong to birds, because penguins do not "fly", so penguins can not inherit birds

Precisely because of this principle, this makes it possible to reuse the parent class only if the subclass can replace the parent class and the function of the Software unit is not affected, and the subclass can also add new behavior on the basis of the parent class. Because the substitution of subclasses makes the modules of the parent class type extensible without modification. It can be said that the principle of the change of the Richter scale makes opening and shutting possible.
as in the case of animals, animals have the behavior of eating, drinking, running, and barking, and if other animals are required to have similar behavior, because they are inherited from animals, only need to change the place of instantiation, the other program is not allowed to change. As shown in:


Five. Dependency inversion principle Dependency inversion principle (dependence inversion Principle) thought: High-level modules should not rely on low-layer modules, both of which should be dependent on abstraction.
1. High-level modules should only contain important business models and policy choices
2. Low-level module is the implementation of different business and strategy
3. High-level abstraction does not rely on the implementation of high-level and underlying modules, up to the lower levels of abstraction
4. Low-level abstraction and implementation are also dependent on high levels of abstraction
In other words: to rely on abstraction, not to rely on concrete implementation, high-level is the function and strategy, the lower layer is concrete implementation, programming language is the need for interface programming, not for implementation programming.
by the way, two knowledge points related to design patterns:
1. Four advantages of object-oriented: maintainable, expandable, ready to take, flexible
2. High cohesion low coupling: High cohesion is a module within each element of a high degree of integration, a software module is only responsible for a task, that is, a single responsibility principle, improve the independence of the module; Low coupling is the low degree of mutual connection between different modules within the software structure, and the modules and modules exist as independently as possible. The interface between modules and modules is as small and simple as possible, with better reusability and extensibility.
Example Understanding: (Strong push & Reference Blog Park cbf4life article--Dependency Inversion principle)
A class diagram that indicates a driver driving a Mercedes Benz car.

The code below shows that the driver drives the car by calling the Mercedes-Benz run method and Eastmount the Mercedes-Benz with the client scene description.
Driver class public class Driver {    //driver main duty driving car public    void Drive (Benz Benz) {        benz.run ();}    } Mercedes class public class Benz {public    void run () {        System.out.printIn ("Mercedes Benz Car Run");}    }  Scene class public class Client {public    static void Main (string[] args) {        //eastmount Mercedes Benz        Driver Eastmount = new Driver ();        Benz Benz = new Benz ();        Eastmount.drive (Benz);    }}
now the driver eastmount not only to drive a Mercedes-Benz car, but also to drive a BMW, and how to achieve it? Custom BMW, but not open, because Eastmount does not open the BMW method, the problem is:
The driver class and Mercedes-Benz class is a tight coupling relationship, which led to a greatly reduced maintainability of the system, the addition of new vehicles such as BMW BWM car will need to modify the driver class drive () method, which is not stable but variable. The change of the dependent person should let the dependent person bear the price of the change, So it can be realized by the dependency inversion principle.
as shown, through the establishment of two interfaces Idriver and ICAR, respectively defined the driver's function is driving the car, through the drive () method, the function of the car is to run, through the run () method to achieve.
The code below, the interface is only an abstract concept, is an abstract description of a class of things, the specific implementation code by the corresponding class to complete, so also need to define the driver implementation class, while in the Idriver interface through the incoming ICAR interface to achieve the dependency between the abstraction, The driver implementation class is also passed into the Icar interface, specifically which vehicle needs to be declared in the high-level model, and the specific development method is defined in the BMW and Benz classes.
//driver Interface Driving car Abstract public interface Idriver {public void drive (ICar car);    Driver class specific implementation public class Driver implements idriver{//driver's main duty is to drive the public void drives (ICar car) {car.run (); }}//Bus interface public interface ICar {public void run ();    Mercedes Benz class public class Benz implements icar{public void run () {System.out.println ("Mercedes Benz Car Run");    }}//BMW class public class BMW implements icar{public void run () {System.out.println ("BMW car Run"); }}//implement Eastmount open BMW public class Client {public static void main (string[] args) {idriver eastmount = new Driver        ();        ICar BMW = new BMW ();    Eastmount.drive (BMW); }}
since "abstraction should not rely on detail", we think that abstract (Icar interface) does not rely on the BMW and Benz two implementation classes (details), in the High-level module application is abstract, the client belongs to the high-level business logic, its dependence on the lower levels of the module is based on abstraction, Eastmount are all based on the Idriver interface type, shielding the effect of detail on the abstract, now open different types of cars, only need to modify the business scenario class can be achieved:
ICar Benz = new Benz ();
Eastmount.drive (Benz);
Dependency inversion can be said to be object-oriented is the logo of the design, in which language to write the program is not important, if the writing is to consider how to focus on abstract programming rather than the details of programming, that is, all the dependencies in the program are terminated and abstract class or interface, that is, object-oriented design, the reverse is a process of design

Six. Interface Isolation principle

Interface Isolation principle (Interface segregation principle,isp) idea: Multiple interfaces with the customer are better than a common interface. If a class has several consumers, instead of letting this class use all of the methods that it needs, Instead, create a specific interface for each consumer and have the class implement the interfaces separately.
Example Understanding: (Recommended & quoted ZHENGZHB blog-- interface Isolation principle )
as shown, Class A relies on interface I method 1\ method 2\ Method 3, Class B is an implementation of Class A dependency, Class C relies on the method method in interface I 1\ method 4\ method 5, Class D is the implementation of Class C dependency. There are methods that are not available for Class B and Class D, but because of the implementation of interface I, So it's necessary to implement these unused methods. (Code see the original link)



It can be found that the interface is too bloated, as long as the interface appears in the method, regardless of the class that depends on it is not useful, the implementation class must implement these methods, such as in class B method 4 and Method 5, Class D in Method 2 and Method 3, it is clear that such a design does not apply.
The design is modified to conform to the interface isolation principle, the interface I must be split, split into three interface I1\i2\i3. Implementing the Methods in Class B and Class D is the only way to use it, which demonstrates the benefits of building a single interface rather than a large interface. (source see the above link)


the principle of interface isolation is to try to refine the interface as little as possible, creating a dedicated interface for each class, rather than trying to build a huge and bloated interface to provide all of the classes that depend on him to invoke. Speaking of which, many people will feel that the interface isolation principle is similar to the previous single principle of responsibility, it is not.
One is that the single responsibility principle focuses on responsibility, while the interface isolation principle focuses on the isolation of interface dependencies.
Second, the principle of single responsibility is mainly constrained class, followed by the interface and method, it is the implementation and details of the program, and the interface isolation principle mainly constrains the interface, mainly for the abstract, for the construction of the overall framework of the program.
    Summary: This is a review of the design model solid Five principles of the article, I like the article in the example, each example is I selected the description mode, through the modom of the single responsibility principle, plus subtraction calculator tells the opening and closing principle, penguin Animals told the Richter replacement principle, The principle of dependency inversion is realized through driver and car, and finally the principle of interface isolation is described. hope that the article to help, especially the students to learn design patterns and code is not too standard or need to reconstruct the classmate, if there are errors or shortcomings, also please Haihan ~
(By:eastmount 2014-11-29 Night 8 o'clock http://blog.csdn.net/eastmount/)
Article reference:
1.<< Advanced Software Engineering >> design mode part of the courseware and the teacher to tell the content
2.<< Design Pattern >> Geoscience
3. Blog Park cbf4life article- dependency Inversion principle
4.ZHENGZHB Blog-- interface Isolation principle

The solid principle of design pattern and look back

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.