Summary and comparison of various design patterns of design patterns


1 goal

1. Briefly analyze the 23 design patterns and design principles of GoF, and make an overall cognition.

2. Analyze Spirng's programming ideas, inspire thinking, and pave the way for in-depth study of Spring in the future.

3. Understand the relationship between various design patterns and solve the problem of design pattern confusion.

2 positioning

1. Master the "Tao" of design patterns, not just "techniques"

2. Dao can be said to be very Dao, dripping water and stone piercing through is not a day's work, so be prepared for long-term practice.

3. Don't use design patterns to apply mechanically, but when encountering problems in business, it is natural to think of design patterns as a solution.

3 Summarize design principles in one sentence

Design Principles one sentence summary Purpose
Open-Closed Principle (OCP) (Open-Close) Open for extension, closed for modification Reducing Maintenance Brings New Risks
Dependence Inversion Principle (DIP) (Dependence Inversion) Higher layers should not depend on lower layers It is more conducive to the upgrade and expansion of the code structure
Single Responsibility Principle (SRP) (Simple Responsibility) A class does only one thing Easy to understand and improve code readability
Interface Segregation Principle (ISP) (Interface Segregation) An interface does only one thing Functional decoupling, high aggregation, low coupling
Law of Demeter (LoD) (Law of Demeter) don't know don't know Only communicate with friends, not strangers, reducing code bloat
Liskov Substitution Principle (LSP) (Liskov Substitution) The function of the subclass overridden method changes, which should not affect the meaning of the parent class method prevent inheritance flooding
Composite Reuse Principle (CARP) (Composite/Aggregate Reuse) Try to use composition to achieve code reuse instead of inheritance Reduce code coupling

4 Introduction to G0F 23 Design Patterns

"Design Patterns: Elements of Reusable Object-Oriented Software" ("Design Patterns"-the book mentioned later), co-authored by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (Addison-Wesley, 1995). These authors are often referred to as the "Group of Four (Gang of Four)", and this book is also known as the "Group of Four (or GoF)" book.

The largest part of the book Design Patterns is a table of contents that lists and describes 23 design patterns. In addition, a number of categories have recently been added to this list, most importantly expanding coverage to more specific problem types. For example, Mark Grand added patterns to solve problems involving issues such as concurrency in Patterns in Java: A Catalog of Reusable Design Patterns Illustrated with UML (that is, the book "Java Edition" mentioned later), and by DeepakAlur. JohnCrupi and Dan Malks Co-authored Core J2EE Patterns: Best Practices and Design Strategies—The book focuses on patterns on multi-tier applications using Java 2 enterprise technologies.

Many people don't notice this. After learning the basic Java language, they go directly to J2EE. Some even rush to fight and use specific J2EE software such as Weblogic. Do you really understand J2EE? Is your application in specific cases also extending the idea of ​​J2EE? The study of software design patterns has resulted in perhaps the most influential book on object-oriented design: Design Patterns.

It can be seen that design patterns and J2EE are in the same line of thought and motivation. I have summarized the following reasons:

  1. The design pattern is more abstract, J2EE is the specific product code, we can touch it, and the design pattern will generate specific code for each application.
  2. The design pattern is a smaller architecture than J2EE and other framework software. Many specific programs in J2EE are completed by applying design patterns. This is especially obvious when you go deep into the internal code research of J2EE. Therefore, if you do not have The basics of design patterns (GoF's design patterns), you can quickly understand J2EE. Can't understand how J2EE can be applied flexibly?
  3. J2EE is just a framework software suitable for enterprise computing applications, but GoF's design patterns can be used in almost any application! Therefore, the design pattern of GoF should be one of the important theoretical foundations of J2EE.

Therefore, the design pattern of GoF is an implicit "bridge" between Java basic knowledge and J2EE framework knowledge.

Design patterns are actually an art. Design patterns come from life, don't use design patterns just to apply design patterns. The design pattern is a solution to the problem that we provide when we are confused, or it can be prevented by using the design pattern well. Since ancient times, when we are at a loss in our lives, we often seek help, or come to consult, or look up the scriptures. Just thousands of years ago, Confucius taught us how to be human. It is known to the Chinese: from the birth of Yuanying, crowned at twenty, standing at thirty, not confused at forty, knowing the destiny at fifty, sixty sixties, seventy ancient and not exceeding the rules, eighty, ninety old... this is what we are In the template mode, of course, some people will not choose this template.

The design pattern summarizes the experience and summarizes the experience of the predecessors, and provides it for future generations to learn from. The predecessors planted trees, and the descendants enjoyed the shade. Design patterns can help us improve code readability and scalability; reduce maintenance costs; solve complex business problems, but don't memorize them by rote. Next, let's first preview the generalization and summary of GOF's 23 design patterns.

Classification Design Patterns
Creational Factory Method, Abstract Factory, Singleton, Prototype, Builder
Structural Proxy, Facade, Decorator, Flyweight, Composite, Adapter, Bridge
Behavioral Template Method, Strategy, Chain of Responsibility, Iterator, Command, State, Memento, Mediator Mode (Mediator), Interpreter Mode (Interpreter), Observer Mode (Observer), Visitor Mode (Visitor)

5 Summary of frequency of use of design patterns

Creational

High Frequency: Factory Method, Abstract Factory, Singleton, Builder

Low frequency: Prototype mode ( Prototype )

Structural pattern (Structural)

High Frequency: Proxy Mode (Proxy), Facade Mode (Facade), Decorator Mode (Decorator), Flyweight Mode (Flyweight), Adapter Mode (Adapter), Combination Mode (Composite)

Low frequency: bridge mode ( Bridge )

Behavioral

High Frequency: Template Method, Strategy, Chain of Responsibility, State

Low frequency: Memento mode (Memento), observer mode (Observer) s iterator mode (Iterator) s mediator mode (Mediator), command mode (Command), interpreter mode (Interpreter), visitor mode (Visitor)

6 — Sentence Induction Design Pattern

Comparison of various design patterns and summary of programming ideas

Design Patterns one sentence summary Purpose life case Framework source code example
Factory pattern (Factory ) Product standardization, production more efficient Package Creation Details physical factory LoggerFactory、 Calender
Singleton pattern (Singleton) There is only one Tom in the world Guaranteed to be unique CEO BeanFactory、 Runtime
Prototype mode (Prototype) Pull out a monkey hair, blow out thousands Create objects efficiently clone ArrayList、PrototypeBean
Builder mode (Builder) High configuration, medium configuration and low configuration, you can choose whichever configuration you want Open Personality Configuration Steps Optional StringBuilder、BeanDefinitionBuilder
Proxy mode (Proxy) I have no resources or time, so I have to find a matchmaker to help Enhanced responsibilities matchmaker ProxyFactoryBean、JdkDynamicAopProxy、CglibAopProxy
Facade mode (Facade) Open a door to the world Unified access portal front desk JdbcUtils、RequestFacade
Decorator pattern (Decorator) His uncle, his second uncle, both are his uncles Flexible expansion, homogeneous pancakes BufferedReader、Inputstream
Flyweight Optimize resource allocation and reduce duplication and waste shared resource pool National Social Security Network String、Integer、ObjectPool
Composite mode People together are called a gang, hearts together are called a team unity of whole and individual Organization Tree HashMap、SqINode
Adapter mode (Adapter) What suits you is the best compatible conversion Power distribution AdvisorAdapten、HandlerAdapter
Bridge Mode (Bridge) Convention over configuration Inheritance is not allowed bridge DriverManager
Delegation mode (Delegate ) This requirement is very simple, I don't care how to achieve it only responsible for the results power of attorney ClassLoader、 BeanDefinitionParserDelegate
Template mode (Template) The process is all standardized, please cover if fine-tuning is required Logic multiplexing put the elephant in the fridge JdbcTemplate、HttpServlet
Strategy All roads lead to Beijing, which one you decide Give the user the choice Select Payment Method Comparator、 Instantiationstrategy
Chain of Responsibility Everyone sweeps the snow in front of the door, don't care about the frost on others Decouple processing logic pass the buck FilterChain、Pipeline
Iterator pattern (Iterator) Sitting on the assembly line for a day, each package is scanned Unify access to collections Check in one by one Iterator
Command mode (Command) In the midst of strategizing, the decisive victory is thousands of miles away Decoupling requests and processing remote control Runnable、TestCase
State mode (State) State drives behavior, behavior determines state Binding state and behavior Order Status Tracking Lifecycle
Memento Give me a dose of "regret medicine" backup hay box StateManageableMessageContext
Mediator I'll give you the contact information, I don't care how to get it done Unified Management of Mesh Resources Circle of friends Timer
Interpreter mode (Interpreter) I want to speak "dialect", all interpretation rights belong to me Implement specific syntax parsing Morse code Pattern、ExpressionParser
Observer pattern (Observer) let me know Decoupling the Observer and the Observed Alarm clock ContextLoaderListener
Visitor pattern (Visitor) Viewed horizontally, it forms a ridge and a side forms a peak, with different heights from near and far Decoupling data structures and data operations KPI assessment FileVisitor、BeanDefinitionVisitor

7 Relationships and comparisons between design patterns

Singleton and factory patterns

In actual business code, the factory class is usually designed as a singleton.

Strategy pattern and factory pattern

1. The factory pattern includes the factory method pattern and the abstract factory pattern are creational patterns, and the strategy pattern is a behavioral pattern.

2. The main purpose of the factory mode is to encapsulate the creation logic, and the strategy mode receives the objects created by the factory to achieve different behaviors.

Strategy pattern and delegation pattern

1. The strategy pattern is an internal implementation of the delegation pattern. Whether the results of the strategy pattern can be replaced by each other.

2. The delegation model pays more attention to the process of distribution and scheduling.

Template Method Pattern and Factory Method Pattern

A factory method is a special implementation of a template method.

在这里插入图片描述

对于工厂方法模式的create。方法而言,相当于只有一个步骤的模板方法模式。这一个步骤交给子类去 实现。而 模 板 方 法 呢 ,将 needHomework方 法 和 checkHomework方法交给子类实现, needHomework方法和checkHomework方法又属于父类的某一个步骤且不可变更。

模板方法模式和策略模式

1、 模板方法和策略模式都有封装算法。

2、 策略模式是使不同算法可以相互替换,且不影响客户端应用层的使用。

3、 模板方法是针对定义一个算法的流程,将一些有细微差异的部分交给子类实现。

4、模板方法模式不能改变算法流程,策略模式可以改变算法流程且可替换。策略模式通常用来代替 if…else…等条件分支语句。

在这里插入图片描述

1、WechatPay、JDPay、AliPay是交给用户选择且相互替代解决方案。而 JdbcTemplate下面的子类是不能相互代替的。

2、策略模式中的queryBalanceOTJ法虽然在pay。方法中也有调用,但是这个逻辑只是出于程序健壮 性考虑。用户完全可以自主调用que「yBalance()方法。而模板方法模式中的mapRow()方法一定要在 获 得 ResultSet之后方可调用,否则没有意义。

装饰者模式和静态代理模式

1、 装饰者模式关注点在于给对象动态添加方法,而代理更加注重控制对对象的访问。

2、 代理模式通常会在代理类中创建被代理对象的实例,而装饰者模式通常把被装饰者作为构造参数。

在这里插入图片描述

装饰者和代理者虽然都持有对方引用,但逻辑处理重心是不一样的。

装饰者模式和适配史器模式

1、 装饰者模式和适配器模式都是属于包装器模式(Wrapper Pattern ) 。

2、 装饰者模式可以实现被装饰者与相同的接口或者继承被装饰者作为它的子类,而适配器和被适配者 可以实现不同的接口。

在这里插入图片描述

装饰者和适配器都是对SiginService的包装和扩展,属于装饰器模式的实现形式。但是装饰者需要满足 OOP的 is-a关系,我们也讲过煎饼的例子,不管如何包装都有共同的父类。而适配器主要解决兼容问 题 ,不一定要统一父类,上图中LoginAdapter和 RegistAdapter就是兼容不同功能的两个类’但 RegistForQQAdapter需要注册后自动登录,因此既继承了 RegistAdpter又继承了 LoginAdapter。

适配器模式和静态代理模式

适配器可以结合静态代理来实现,保存被适配对象的引用,但不是唯一的实现方式。

适配器模式和策略模式

在适配业务复杂的情况下,利用策略模式优化动态适配逻辑。

Guess you like

Origin blog.csdn.net/ZGL_cyy/article/details/129109815