preface
Understand design patterns of classmates know, members of the family of design patterns is very large, concrete can be divided into three categories, a total of 23 design patterns for us, some design patterns on the species is more, and many design patterns are very similar, let a person silly points not clear This paper mainly introduces some confusing design patterns, to deepen the understanding of design patterns
This article mainly includes the following contents
- The introduction of six design principles
- Differences between simple factories, factory methods, and abstract factory patterns
- Differences between proxy, decorator and adapter patterns
- The difference between policy, state, and command mode
Introduction to Design Principles
As we all know, there are generally six of the five principles of design
- Single responsibility principle (
Single Responsibility Principle, SRP
) - Open and close principle (
Open Close Principle, OCP
) - Richter’s substitution principle (
Liskov Substitution Principle, LSP
) - Dependency inversion principle (
Dependence Inversion Principle, DIP
) - Interface isolation Principle (
Interface Segregation Principle, ISP
) - Demeter’s law (
Law of Demeter, LoD
), also known as the least knowledge principle (Principle of Least Knowledge
)
The first five principles are called SOLID principles
Single responsibility principle
The single responsibility principle is simple and easy to understand: a class should have a single responsibility, and a method should only do one thing, but I won’t go into that here
The open closed principle
The open-closed principle says that programs are open for extension, but closed for modification: when your program needs to be extended, you should not modify the original code, but add a class to extend it. For example, if an item is discounted, you can change the getPrice method of the original item class, or you can add a subclass that overrides the getPrice method and uses the subclass when the item is discounted through a higher-level module.
The idea of the open and closed principle is to encapsulate what doesn’t change, expose what doesn’t change, so they don’t get mixed up, and you can reuse what doesn’t change, and increase extensibility. The advantage of the open and closed principle is that the original code doesn’t change, and you can reuse the original code
Richter’s substitution principle
The Reefer substitution principle is described in one sentence: all references to a base class must be able to be replaced directly with its subclasses. In other words, all references to a base class must transparently use its subclass objects. But this seems a little strange, because in Java, references to base classes can be replaced by subclasses, so why the rule? This is because subclasses can override the methods of their superclass, and if the superclass has an addition method that is overwritten as subtraction in a subclass, it can cause unexpected problems if you replace the superclass with a subclass
Richter’s substitution principle tells us that inheritance actually strengthens the coupling of the two classes. Try not to rewrite the methods of the parent class in the subclass. In appropriate cases, aggregation, composition, and dependency can be used to solve the problem. If the subclass needs to override the methods of the parent class, the original inheritance relationship can be removed. Both the parent class A and subclass B inherit A more popular base class. If B needs to use the methods of A, it can be implemented in A combined way
Dependency inversion principle
Dependency inversion is: A high-level module should not depend on a low-level module, but both should depend on an abstract interface such as a Person class that needs to collect information, a Message class, in this case a high-level module, Message is a low-level module dependency inversion, which means that Person should not rely on a concrete implementation of Message, but should rely on an abstract interface for subsequent extension
So dependency inversion is interface-oriented programming, but that’s not a very good name
Interface Isolation Principle
The interface isolation principle can be summarized as follows: Interface classes should not rely on it don’t need, that is, a kind of dependence on another class should be based on the minimal interface This as compared with single responsibility principle, the single responsibility principle for responsibility, from the business logic, and the interface segregation principle requires the method of the interface as little as possible Feel this principle with minimum knowledge and more like a class should not know things you don’t need it
Principle of least knowledge
The principle of minimum knowledge is also easy to understand: one object should know the least about other objects. The principle of minimum knowledge puts forward a clear requirement for low coupling of classes
Differences between simple factories, factory methods, and abstract factory patterns
The factory pattern is one of the patterns we use most often, but since it can be broken down into three categories, it can be confusing. Let’s list their definitions first:
- Simple Factory pattern: Also known as static method factory pattern, a factory object decides which instance of a product class to create.
- Factory method pattern: Create a user-created object interface and let subclasses decide which class to instantiate. The factory method delays the initialization of a class to its subclasses.
- Abstract Factory pattern: Provides an interface for creating a set of related or interdependent objects without specifying their concrete classes.
Three modesUML
Figure as follows
And you can see that the main difference is
- Simple Factory pattern: A factory method creates objects of different types
- Factory method pattern: A concrete factory class is responsible for creating a concrete object type
- Abstract Factory pattern: A concrete factory class is responsible for creating a series of related objects
Differences between proxy, decorator and adapter patterns
Among structural design patterns, the similar and confusing patterns are agent, decorator, and adapter. First, let’s list their definitions and UML diagrams.
- Proxy mode: Provides a proxy for other objects to control access to that object
- Decorator mode: To dynamically add some additional responsibilities to an object, decorator mode is more flexible in terms of adding functionality than subclassing
- Adapter pattern: Transforms the interface of one class into another interface that the client expects so that two classes that would otherwise not work because of interface mismatches can work together
Three modesUML
The figures are as follows:
The main differences are:
- The proxy mode is characterized by isolation. It isolates the relationship between the calling class and the called class, and calls through a proxy class. Therefore, the proxy mode does not need to pass in the original object, but internally holds the implementation of the original object
- The decorator pattern is characterized by enhancement. The decorator pattern is characterized by the fact that the decorator class and all decorator classes must implement the same interface, and must hold the decorator object, which can be decorated indefinitely, passed in through the constructor
- Adapters are characterized by compatibility. The adapter pattern needs to implement the new interface, the proxy and decorator pattern implements the same interface as the original object, and the adapter class matches the new interface
In general, it is the following three sentences:
- The proxy mode combines a class (
a
) to a concrete action class (b
). - Decoration mode is performed in an existing class (
a
) added some new functionality to become another class (b
). - The adapter pattern is to combine a class (
a
) to another class in some way (b
).
The difference between policy, state, and command mode
Policy, state, and command patterns, all behavioral design patterns, are similar in structure and can be confusing. Let’s first look at their definitions and UML diagrams
- Policy pattern: Define a set of algorithms, encapsulate each algorithm, and make them interchangeable
- State mode: The behavior in the state mode is determined by the state. Different states have different behaviors. Allows an object to change its behavior when its internal state changes, and the object appears to modify its class.
- Command mode: Encapsulates a request as an object, allowing you to parameterize the client with different requests, queue requests or log requests, and provide command undo and recovery functions
itsUML
The figure is shown below
We can see that the class diagrams of policy and state patterns are actually the same. Although they are the same type of interface, they are different in nature. Don’t focus on structure. The three modes differ mainly in intent:
- Strategy pattern: Strategy pattern is concerned with algorithm replacement, replace the old algorithm with a new algorithm, or provide a variety of algorithms to be selected by the caller, algorithm free replacement is the focus of its implementation
- State mode: State mode Policy mode is similar in that it encapsulates the “state” of the class and replaces the action accordingly. Thus, the same action of the class in different states shows different results. It differs from the strategic pattern in that the transition is “automatic” and “unconscious”. Policy mode controls which policies the object uses, while state mode automatically changes the state. The state mode internally maintains a state that will follow
public api
Call to the corresponding state transition. The outside world doesn’t need to know about states and how they change. - Command mode: The command mode focuses on the decoupling problem. How to decouple the requester and the executor is the first thing it needs to solve. The decoupling requirement is to encapsulate the content of the request into one command and execute it by the receiver. Because the command is encapsulated, multiple processes can be performed on the command at the same time, for example through unified
execute
The interface executes commands or stores the commands for subsequent revocation or recovery
For a specific example of comparing policy patterns with state patterns, see Policy patterns vs. state patterns
conclusion
This article mainly introduces the six principles of design patterns, as well as several similar confusing design patterns. Hope that through the analysis and comparison of these several easily confused design patterns, more in-depth understanding of their similarities and differences and applicable scenarios, deepen the understanding of design patterns
The resources
Overview of Design Patterns: Six design principles Confusing design patterns Adapter patterns, decorative patterns, proxy patterns Similarities and Differences Policy patterns vs. state patterns