Re-learning design patterns (four, design pattern summary)

1. Summary of Design Patterns

    So far, we have completed the study of 23 design patterns, and it is necessary to make a summary at the end.

    Design pattern is not a specific technology, it tells the idea of ​​solving problems , it is a set of solutions to improve code reusability, maintainability, readability, robustness and security, and it is a full understanding and application of class encapsulation, inheritance and polymorphism, as well as class association and composition relations .

    There is a concept in software engineering called high cohesion and low coupling , which is one of the criteria for judging the quality of a software design.

   High cohesion : Cohesion is aimed at the internal design of the module, and refers to the degree to which elements in a software module are combined with each other. High cohesion means that the elements in a module are closely combined with each other. To put it simply, it is whether a module is composed of highly correlated code, without redundancy and overly complicated logic, and is only responsible for one task, which is often said to conform to the principle of single responsibility.

    Low coupling : Coupling refers to the complexity of interaction between modules (or classes) and modules (or classes). The degree of coupling between modules depends on the complexity of the interface between modules, the way of calling, and the transmission of information. The less information transmitted, the lower the degree of coupling.

    High cohesion and low coupling can ensure the independence of services and the flexibility of the system. Therefore, the core idea of ​​​​our learning design patterns coincides with it-decoupling (reducing designs that may increase coupling).

    Both the front-end and the back-end are tending to be componentized, and even microservices have been born in the application architecture, and the ideas of componentization and microservices are the embodiment of high cohesion and low coupling.

    The core idea of ​​our learning design patterns is decoupling , not eliminating coupling, but controlling the coupling within a certain range, finding stable points and changing points, and using abstraction to isolate the changing points. Satisfy the design principles first, and then iterate out the design patterns .

    In fact, all design patterns have something in common (in java, it is the comprehensive application of abstraction, inheritance, polymorphism, and combination). Some of them look very similar but can solve different problems.

Disclaimer: Original articles may not be reproduced without permission! ! !

1.1. Summary of Design Principles

in principle definition Purpose application
Single Responsibility Principle - SRP A class should have one and only one reason for its change, otherwise the class should be split Functional decoupling For example: Divide user information into attribute classes and behavior interfaces, and a Dao represents a table
Open-Closed Principle-OCP A software entity (such as a class, module, function, etc.) should be open for extension and closed for modification Reduce the risk of maintenance
Liskov Substitution Principle - LSP Inheritance must ensure that the properties owned by the superclass still hold in the subclass prevent inheritance flooding For example: the add()-method in the parent class is rewritten by the subclass as the subtraction()-subtraction function, so there is no need to use the inheritance relationship
Interface Segregation Principle - ISP An interface only does one thing, the interface should be thin but not fat Functional decoupling
Dependency Inversion Principle - DIP Program to the interface, not the implementation Functional module decoupling For example, the application of the idea of ​​inversion of control (dependency injection) generally includes construction injection, set injection or annotation injection. Because it is an interface, different implementation classes can be passed, so injection is meaningful.
Law of Demeter-LOD Don’t know what you shouldn’t know, reduce coupling and complexity Functional decoupling For example: Appearance mode and intermediary mode are its applications
Principle of Synthetic Reuse - CRP Use object composition first to achieve code reuse, followed by inheritance Reduce code coupling

    Detailed article link: Re-learning Design Patterns (Design Principles)_Mu Jinxuan's Blog

1.2. Summary of Design Patterns

1.2.1. Creational Design Patterns

model definition Purpose application article link
Singleton Pattern A class has only one instance, while providing a global access point to that instance Guarantee global uniqueness and save memory Configuration information and resource access conflicts of the main application systems; such as: tomcat's ServletContext, Spring's default injection, logging, thread pool, etc.; Relearn Design Patterns (Singleton Patterns)
Prototype Pattern Create new objects by copying prototypes Create objects efficiently Use cloning when creating a complex or very resource-consuming object to avoid repeated creation; there are two ways to create beans in Spring: singleton mode and prototype mode; Relearn Design Patterns (Prototype Patterns)
Factory Pattern Create different instances under different conditions Encapsulate complex creation logic Unified management, delaying the instantiation of objects, such as: BeanFactory; DocumentBuilderFactory when XML parsing; Relearn Design Patterns (Factory Patterns)
Builder Pattern Transfer the construction logic of the class to the outside of the instantiation of the class to achieve Separate complex construction from presentation The append method of StringBuilder; PreparedStatement in SQL; DomBuilder and SAXBuilder in JDOM; Relearn Design Patterns (Builder Patterns)

1.2.2. Structural design pattern

model definition Purpose application article link
Adapter Pattern Allow objects with incompatible interfaces to cooperate compatible conversion For example: old system upgrade; java.io.InputStreamReader(InputStream java.io.OutputStreamReader(OutputStream) Relearn design pattern (-adapter pattern)
Proxy Pattern Provides a proxy for other objects to control access to this object Enhanced responsibilities JDK automatic dynamic proxy: implementation of interceptors in java.lang.reflect.Proxy struts2 and mybatis; implementation of AOP in Spring; Re-learn design pattern (-proxy pattern)
Bridge Pattern Separate the abstraction from the implementation so that they can vary independently Decoupling abstraction from implementation JDBC driver; log classification; Relearn Design Patterns (Bridge Pattern)
Composite Pattern¶ Guarantee the consistency of the client with a single object and a composite object unity of whole and part The container in the GUI; the organizational structure of the OA system; Relearn Design Patterns (Composite Patterns)
Facade Pattern Provide a unified entry point for multiple complex subsystems Simplify client calls Tool classes provided by Hibernate, Spring JDBC tool classes; Relearn Design Patterns (Appearance Patterns)
Decorator Pattern The function of adding/modifying objects at runtime is more flexible than generating subclasses Enhanced functions Design of IO flow in java; Design of request object in servlet; Relearn Design Patterns (Decorator Patterns)
Flyweight Pattern Cache objects by sharing to reduce memory consumption Optimize resource allocation Thread pool, database connection pool; String class design; Re-learning Design Patterns (Flyweight Pattern)

1.2.3, behavioral design pattern

model definition Purpose application article link
Template Pattern Implement an algorithm in a method, and defer defining certain steps in the algorithm, allowing other classes to redefine them Logic multiplexing Provide extension points for some fixed process classes; doGet/doPost call in javax.servlet.http.HttpServlet Relearn Design Patterns (Template Method Pattern)
Strategy Pattern Separation algorithm, choose implementation Transfer of options Layout management in GUI (for example: flow layout, grid layout, etc. can be selected); Resource interface resource access strategy in Spring; Relearn Design Patterns (Strategy Patterns)
Command Pattern Separation of the request and the responsibility for executing the request facilitates the management of storage, transfer, and invocation of the request Decoupling requests and processing Database transaction processing mechanism; command undo and recovery; Relearn Design Patterns (Command Patterns)
Chain of Responsibility Pattern A standalone object that converts specific behaviors into handlers Decoupling the sender and receiver of requests Exception handling mechanism in java (try-catch); chain processing of filters in Servlet; event bubbling and capture mechanism in javaScript; Relearn Design Patterns (Chain of Responsibility Pattern)
State Pattern Distribute the logic representing the state of an object into different classes that represent the state Binding state and behavior Thread object state switching javax.faces.lifecycle.LifeCycle#execute() Relearn Design Patterns (State Patterns)
Observer Pattern It mainly solves the problem that there is a one-to-many dependency relationship among multiple objects, and when an object changes state, it notifies other objects Decoupling the Observer and the Observed Observers provided in JDK java.util.Observer/ java.util.Observable; java.util.EventListener; Relearn Design Patterns (Observer Pattern)
Mediator Pattern Unified management of objects (a large number of many-to-many relationships) through the intermediary, and the interaction between objects is encapsulated in the object of the intermediary Reduce coupling between objects C-Controller in MVC pattern, with MV connected; java.util.Timer; java.lang.reflect.Method#invoke() Relearn Design Patterns (Meditor Pattern)
Iterator Pattern Provides a way to access elements of an aggregate object without exposing its underlying representation Unified access to collections JDK's built-in collection container uses iteration Relearn Design Patterns (Iterator Patterns)
Visitor Pattern Stabilize data structures and define new operational behaviors Decoupling data structures and data operations Can act as an interceptor; java.nio.file.FileVisitor-SimpleFileVisitor; Relearn Design Patterns (Visitor Pattern)
Memento Pattern Save the state of the object and restore it when needed backup, restore The rollback operation of the transaction; the history record in photoshop; Relearn Design Patterns (Memo Pattern)
Interpreter Pattern Given a language, define its grammatical representation, and define an interpreter that uses this identifier to interpret sentences in the language Implement specific syntax parsing Regular expressions, EL expressions, mathematical expressions; some custom parsing rules; Relearn Design Patterns (Interpreter Patterns)

Guess you like

Origin blog.csdn.net/xiaoxianer321/article/details/125573114
Recommended