So without further ado, let’s take a look at a mind map





Understanding the SOLID principle

Whether it is software system design, or code implementation, follow effective and clear design principles, are conducive to flexible and reliable system software, safe and fast landing, more importantly, flexible response to demand, simplify system expansion and maintenance, avoid invalid overtime. This article focuses on the most popular design principle in object-oriented software development, SOLID, which is an acronym for five design principles for easy memorization:

  • Single responsibility principle
  • Open/closed principle
  • Omega substitution principle
  • Interface Isolation Principle
  • Dependency inversion principle
But there is another Demeter: is a main mode changes, should as far as possible the impact of other modules, but the rules, I feel myself, normal developers should all know this, so, just in the mind map to show, not alone shows, mainly the remaining five principles today

S: Single Responsibility Principle (SRP)



The basic concept

The Single Responsibility Principle (SRP) is one of the simplest and most difficult principles to apply. Its definition is simple: there should be only one reason for a class to change. The reason for the change represents the responsibility of the class, which may be a domain-specific function or a solution to a requirement. The principle is not to give a class too much responsibility, once there are multiple responsibilities, then it is easier to change because of one responsibility, such a state is unstable, inadvertent changes are likely to affect the other functions of the class. Therefore, we need to encapsulate different responsibilities in different classes, that is, encapsulate different reasons for change in different classes, and the changes between different classes do not affect each other.



Example is given to illustrate

To take a specific example, a class that implements editing and printing a report changes for two reasons: First, the content of the report can be changed (edited). Second, the format of the report can be changed (printed). If there is a change to the report editing process, the report editing process will cause a change in the common state or dependencies, making the code for the print function not work. So the single responsibility principle says that the cause of these two changes is actually two separate functions that should be separated in separate classes.







Related design patterns

In the face of the program code violating the principle of single responsibility, we can use appearance mode, agent mode, bridge mode, adapter mode, command mode to reconstruct the existing design, to achieve the separation of multiple responsibilities.



summary

The single responsibility principle is used to control the granularity of a class, reduce the code coupling of unrelated functions in the class, and make the class more robust. In addition, the principle of single responsibility is also applicable to module decoupling, which has great guiding significance for module function division.



O: Open close Principle (OCP)



The basic concept

The open-Closed Principle (OCP) is the Open Closed Principle, which states that software objects (classes, modules, functions, etc.) should be Open for extension but Closed for modification. Open to extension here means that adding new code allows the program to expand to meet changing requirements; Closed to modification means that you do not modify existing code while extending the behavior of the program to avoid affecting existing functionality. The key to changing the behavior of the system without changing the code is abstraction and polymorphism, defining the abstraction layer of the system through interfaces or abstract classes and extending it through concrete classes. In this way, there is no need to change the abstraction layer, only need to add new concrete classes to implement the new business function, to meet the requirements of the open closed principle.



Example is given to illustrate

Also, for example, to further understand the closed principle of geography: there is a Display class for chart Display, which can draw various types of charts, such as pie charts, bar charts, etc. When a particular chart needs to be drawn, it strongly depends on the corresponding type of chart. The internal implementation of Display class is as follows:

public void display(String type) {
    if (type.equals("pie")) {  
      PieChart chart = new PieChart();  
      chart.display();  
    }  else if (type.equals("bar")) { BarChart chart = new BarChart(); chart.display(); }}Copy the code
Based on the above code, if you need to add a new graph, such as line graph LineChart, you need to modify the Display () method of the Display class to add judgment logic, which clearly violates the open and close principle. AbstractChart class AbstractChart class AbstractChart class AbstractChart class AbstractChart class AbstractChart class AbstractChart class AbstractChart class AbstractChart class AbstractChart class AbstractChart class AbstractChart class AbstractChart class AbstractChart class AbstractChart class AbstractChart class AbstractChart class

private Abstractchart chart;

public void display() {
    chart.display();  
}

Copy the code
Now we need to add a LineChart Display by injecting a LineChart object into Display on the client side without modifying the source code of the existing class library.







Related design patterns

Face against the open closed principle program code, can use the design patterns are many, such as a factory pattern, observer pattern, the template method pattern, strategy pattern, combination mode, use the design patterns of the key point is to identify the most likely to change and extension, and then construct the abstract to isolate these changes.



summary

With the open closed principle, requirements oriented change can be quickly adjusted to implement functionality, which greatly improves system flexibility, reusability, and maintainability, but adds some complexity.



L: Li substitution principle (LSP)



The basic concept

Basically defined as the Liskov Substitution Principle, everything that uses a base class can be replaced with objects that subclass it, without compromising the correctness of the program. When we pass a subtype object, we need to ensure that the program will not change any behavior and state of the original base class, and the program can operate normally.



Example is given to illustrate

To understand the li substitution principle, here is a classic example of a violation of the Li substitution principle: the square/rectangle problem.





The Square class inherits the Rectangle class, but the width and height of the Rectangle class can be changed separately, whereas the width and height of the Suqare class must be changed together. An error occurs when the User class operates on a Rectangle of type Suqare:

Rectangle r = ... ; // return the object of the specific type r.setwidth (5); r.setHeight(2); assert(r.area() == 10);Copy the code
An assertion of area 10 fails when it returns an object of type Suqare, which clearly violates the li substitution principle.



summary

In order to make the program code comply with the rule of In-substitution, it is necessary to ensure that when the subclass inherits from the parent class, except adding new methods to complete the new functions, try not to rewrite the methods of the parent class. In other words, the subclass can extend the functions of the parent class, but cannot change the original functions of the parent class. Substitution principle, on the other hand, the type IS also split the supplement of the closed principle not only applies to the inheritance, also applies to the design of the relations, IS often mentioned – A relationship IS to the behavior, if the two type of behavior IS not compatible, so you should not use inheritance, better way IS to extract the public part of the way to take the place of inheritance.



I: Interface Isolation Principle (ISP)



The basic concept

Interface Segregation Principle (ISP) : A client should not rely on interfaces that it does not need. The client should only rely on the methods it actually uses, because if an interface has several methods, it means that its implementation classes implement all the interface methods, which is very bloated in code structure.



Example is given to illustrate





Now let’s look at an example of interface isolation violation. From the class diagram above, there are multiple users that need to operate on the Operation class. If User1 only needs to use the operation1 method, User2 only needs to use the operation2 method, and User3 only needs to use the operation3 method, then obviously for User1, The operation2 and operation3 methods should not be seen. Reduce your dependence on methods you don’t care about and prevent changes to the operation2 and Operation3 methods in the Operation class from affecting User1’s functionality. This problem can be solved by isolating the different operations into separate interfaces, as shown in the figure below.





Based on the interface segregation principle, we need to do is to reduce the interface definition instead of, class to implement interface should be broken down into multiple interfaces, then according to the required functionality to achieve, and where the use to the interface method, with the corresponding interface type to declare that it can remove the caller and the dependence of unrelated object method. In summary, the main function of the interface isolation principle is to control the granularity of the interface, prevent the exposure of unrelated code and methods to the client, ensure the high cohesion of the interface, reduce the coupling with the client.



D: Dependence inversion Principle (DIP)



The basic concept

Dependency Inversion Principle (DIP)

  • High-level modules should not depend on low-level modules, but should co-depend on abstractions;
  • Abstractions should not depend on details, details should depend on abstractions.
The abstractions here are interfaces and abstract classes, and the details are the classes that implement interfaces or inherit abstract classes.



Example is given to illustrate

How to understand “high-level modules should not depend on low-level modules, but should co-depend on abstractions”? If the higher-level modules depend on the lower-level modules, the changes in the lower-level modules are likely to affect the higher-level modules and cause the higher-level modules to be forced to change, making the reuse of the higher-level modules very difficult.





The best way to do this is to build a stable abstraction layer in the high-level module and rely only on this abstraction layer. The implementation details of the abstraction layer are completed by the underlying module. In this way, the high-level classes all use the next layer through this abstract interface, removing the high-level’s dependence on the low-level implementation details.



Related design patterns

Regarding the dependency inversion principle, design patterns that can be used include factory pattern, template method pattern, and policy pattern.



summary

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. At the same time, relying on inversion principle is also the core principle of framework design, good at creating reusable framework and extensible code, such as Servlet specification implementation of Tomcat container, Spring Ioc container implementation.



conclusion

Here, SOLID design principles are all introduced, the main purpose of this paper is to systematically organize and summarize the six principles, in the subsequent process of programming and development can consciously identify the design principles and patterns. If you have more ideas and understanding of the design principle, welcome to leave a comment, we discuss together.



If you need the mind map above, click “like” and follow it, you can view the way to obtain the private message “information”

Welcome everyone to pay attention to the public number: Java Architects Alliance, updated daily technical good articles