preface

The essence of design patterns is to find change and encapsulate it. In order to do this, led to a lot of design principles, such as a single principle, simple principle, the principle of minimum principle, the expression, responsibility principle, object oriented principles, the principle of inversion, the principle of practice, separation principle, contract principle, of course, there are some thinking, such as combination of thinking, hierarchical thinking and engineering thinking, object, iterations, and so on.

directory

I. Six design pattern criteria

  • Single responsibility
    • The responsibilities of classes should be single, with a method doing only one thing, and each change to the smallest unit of methods or classes should have only one reason for the change
  • Richter’s substitution principle
    • All references to the base class must be able to be replaced directly by its subclasses
    • A child inherits from its parent class and overrides the method
    • When overwriting a superclass method, the output can be shrunk and the input can be enlarged
  • Dependency inversion
    • High-level modules cannot depend on low-level modules; both should depend on their abstractions
    • Abstract for Java is abstract class, interface, detail is implementation class, detail should depend on abstraction. Interface-oriented and abstract programming can reduce the coupling between classes and improve stability.
  • Interface isolation Rule
    • A client should not rely on interfaces it does not need; an interface should try to serve only one submodule or business logic
    • Interfaces need to be highly cohesive to reduce external interaction
    • The design needs to be limited, the smaller the design granularity, the more flexible, but the structure will be very complex.
  • Demeter’s law
    • The least knowledge principle, in which an object should know the least about other objects, makes explicit requirements for low coupling of classes
  • The open closed principle
    • Open for extension, closed for modification
    • Abstract elements, encapsulating changes

2. Design pattern types

  • Creative design patterns

    • Focusing on the internal structure of an object, often a combination of interfaces and implementations
  • Structural design mode

    • The focus is on how multiple objects are combined
  • Behavioral design patterns

    • The concern is the internal algorithm of an object and the assignment of responsibilities and responsibilities between objects, for example, the concrete implementation of an algorithm, selection strategy, state changes, and other abstract concepts.

    • There are also two types of behavioral patterns.

      • Class behavior pattern: Use inheritance to relate behavior between classes.

      • Object behavior pattern: Use composition or aggregation to allocate behavior between different classes.

3. Design pattern

1. Create patterns

The singleton pattern

It is common to enforce unique object creation, along with common singleton thread-safety issues

Builder mode

Builder mode, focus on how to achieve the combination of object creation process, for a lot of parameters, we will consider to use The Builder mode, and then in the final build, create an object, to achieve the polymorphic object creation process.

Abstract Factory pattern

The focus is to create a family of factory objects that implement a unified abstract product, essentially in order to find the right abstract product and ensure consistency between the factories of the objects being created

Factory method pattern

The creation time of the object is delayed to each specific factory, let the specific factory solve the complex object creation process, and define the interface, to ensure that the creation of the object can be arbitrary replacement line, to achieve the creation of the object polymorphism

The prototype pattern

Through replication, the object copy can be quickly established, and the runtime object capability can be dynamically extended, which realizes the polymorphism of object copy

2. Structural mode

Adapter mode

  • The transformation between different interface functions is implemented, and the source role is transformed into the target role

The bridge model

  • Abstraction and implementation are separated. Implementing a permanent binding between abstract entities and abstract behaviors can be understood as designing behavior that may change based on existing artifacts

Portfolio model

  • The difference between a single object and a composite object can be ignored in expressing the relationship between whole and parts. It actually uses a tree-like structure, leaf nodes, combination nodes

Decorative pattern

  • Adding some additional responsibility to an object dynamically, unlike inheritance, implements polymorphism of interface functions through proxy, avoiding a large number of subclasses. It works well with chain and tree structures, but tends to be overly coupled between objects and decorators.

Facade pattern

  • Used to provide a uniform interface to subsystems. Unlike the mediation pattern, the focus is to provide an external access interface that does not allow any access to subsystems other than the interface

The flyweight pattern

  • It is used to solve the problem of resource loss caused by repeated creation of large objects, and reuse objects by sharing object pool

The proxy pattern

  • The structure of the pattern is very similar to that of the decorative pattern, but with a different emphasis, one on modifying the behavior of an object and the other on controlling access.

3. Behavioral patterns

Visitor pattern

  • It is actually a tree structure at the object level, similar to the abstract factory pattern. It provides a unified way for users to access the data nodes in the tree structure, so it has the characteristics of flexible extension

Template method pattern

  • Define an algorithm template and defer the execution steps to subclasses

The strategy pattern

  • Multiple different algorithms are encapsulated into strategies, so that they can be replaced with each other, suitable for computing efficiency requirements of the system. The policy pattern is often used in conjunction with the factory method pattern to provide users with a set of usage policies

The state pattern

  • The most common implementation is the state machine, which is widely used in systems that need to control the flow of state. Used in games, workflow engines, shopping processes, etc

Observer mode

  • The observer pattern focuses on decoupling the observer and observed code, while the mediator focuses on acting as a new medium between the two objects

Memorandum Mode

  • Also known as snapshot mode, it is usually used to capture the internal state of an object, such as save, open, close, etc., and save a copy of the state outside the execution object, which can be easily used to restore the object to a certain time state later

The mediator model

  • The biggest effect is to decouple direct references between objects. The design idea is much like the layering idea. By introducing an intermediate layer, the many-to-many relationship between layers becomes a many-to-many relationship

Iterator pattern

  • It is widely used in base class libraries to encapsulate repeated traversal operations. Most programming languages now provide off-the-shelf iterators that you can use

Interpreter mode

  • Define a syntax representation for a language (programming languages are languages), such as if-else syntax, regex, and define an interpreter to process this syntax

Command mode

  • To pass a command (function method) as an object, focus on the dimension of the command, for example, the command to open and close a file. For scenarios that handle multiple command invocations and use remote services

Chain of responsibility model

  • Dynamically specify the responsibility of the object, by the object to achieve the corresponding responsibility

Iv. Comparison of design patterns

1. Create class patterns

The factory method pattern and the builder pattern

The factory method pattern focuses on the method of creating the overall object, while the Builder pattern focuses on the process of building the component object, with the goal of creating a complex object through precise construction step by step.

For example, to build a car, through the factory method, directly produced a car can be driven, while through the builder model, need to step by step assembly, assembly of a car before it is generated.

Abstract the factory and builder patterns

The abstract factory pattern implements the creation of a product family. A product family is a set of products: a combination of products with different categorical dimensions, not concerned with the construction process, but with what products are produced by what factory. The builder model is still a process to create products and assemble new products.

2. Structure class pattern

Agent and decorator patterns

The similarity between the two is that they both have the same interface. The difference is that the proxy pattern focuses on the control of the agent process, while the decoration pattern focuses on the enhancement or reduction of class functionality, focusing on the change of class functionality.

Decorator pattern and adapter pattern

Both are wrapper functions that implement their functions in the form of class delegation. The decorator pattern wraps its sibling classes, which belong to the same interface or parent class, while the adapter pattern is a transformation between two unrelated roles that disgusts non-family objects as family objects, which are not essentially the same interface.

3. Behavioral patterns

Command mode and policy mode

The emphasis of the strategy pattern is on the encapsulation algorithm, and the algorithm is considered as a complete and indivisible atomic business. The purpose is that algorithms can be independent and interchangeable. However, the Command mode is the decoupling of the action, dividing the execution of an action into execution object (Command receiver, the specific execution process of the final Command) and execution behavior (each Command role Command), so that the two are independent of each other without any influence.

Policy mode and state mode

The focus of the strategy mode is the encapsulation algorithm. There is no interaction between the algorithms and the algorithms can be switched freely. The state mode encapsulates the state to achieve the purpose of state switching and behavior change as it occurs.

Observer pattern and chain of responsibility pattern

In the observer mode, a specific role can be either the observer or the observed. Both of these two modes will generate triggering chains for transaction processing, that is, business processing flow and chain-like processing, but the distribution channels of messages are different, and the relationship between the upper and lower nodes is also different (there is no upper and lower node relationship in the chain of responsibility, but the relationship between the upper and lower nodes in the chain of responsibility is very clear).

4. Comparison between other modes

Policy mode and bridge mode

The bridge pattern focuses on the separation of abstraction and implementation, so that both the implementation abstraction and the implementation can be independently extended as long as they inherit from the abstract class.

The facade model and the intermediary model

The facade pattern focuses on providing a unified access point to a complex subsystem, defining a high-level interface that prevents external modules from going deep into the subsystem and coupling with internal details. The mediator pattern uses a mediator object to encapsulate the interaction of a series of colleague objects, so that references between the objects are no longer visible.