Design pattern learning record


Recently, I have studied design patterns. Here I record my understanding of design patterns.

Principles of design pattern

1. Single responsibility principle

A class or method only does one thing, or has only one role. For example, a SMS tool class is only responsible for SMS related.

(to expand, when a class or method is written, what each module does should be at a level, that is to say, there are three steps of one thing: 1, 2, and 3. Each step has a small step, which should be put into a sub method or subclass. The current module is responsible for the integration of steps 1, 2 and 3. PS: in the code neatness way, record here)

2. Interface isolation principle

A class inherits an interface. The methods of the interface should be available in subclasses. Otherwise, the unnecessary parts can be split into other interfaces

3. The principle of reliance reversal

When a class is new, try to use its parent to receive it. In a system, members of a class should not be subclasses of the same level class.

4. Ritz’s substitution principle

Specification means that the subclass cannot change the non abstract methods that cover the parent class. When overloading the parent method, the input parameters can be more relaxed (I didn’t understand at the beginning, but later I reflected that the parameter using the parent class is called overload, which is another method. It is equivalent to that the child class has two methods, and the parameter is less than or equal to the child class, that is to say, covering the parent method, which violates the historical conversion principle). The goal is to replace all parent classes with any subclass that can be used

5. Open close principle

The function has been extended and the original function has not been affected

6. Dimitar’s law

Only communicate with direct friends. Direct friends refer to member variables, method parameters, and member parameters in the return type. If there is a type in a method that is not all the member variables of this class, any one of the method parameters and return types violates dimitt’s law

Of course, these principles are similar to the three paradigms of database. Blindly abiding by these principles is not necessarily efficient and concise code, or it needs to master a degree.

2、 Design patterns

1. Singleton mode

The singleton mode includes lazy and hungry mode. Lazy man refers to creating when necessary, while hungry mode refers to creating when the program is running.

Singleton mainly includes static variables, enumerations, double locks and static inner classes. The first two are immediate loading, which is called starving Chinese style, while the latter two are loading at execution time, which is lazy.

2. Factory model

Factory pattern is divided into simple factory, factory method and abstract factory.

A simple factory is a factory pattern that can create multiple objects. The problem is that this method requires multiple switch or if else branches, which does not conform to the open close principle.

The factory method has an abstract factory parent class that creates different factory instances for each object. (PS: I haven’t understood before. I think the factory method still needs to go to if Else decides which factory to use. It is no different from a simple factory. Now I understand that the place where an instance is created usually specifies what instance needs to be created when writing the code. In this case, the simple factory still needs the conditional branch to select what object to create, and the factory method only needs to directly use the factory of the corresponding object).

The difference between an abstract factory and a simple factory is that a simple factory can only create one object, while an abstract factory can create a group of objects.

3. Prototype pattern

Prototype patterns are almost instances of replicated objects, and the main thing to understand is shallow copy and deep copy. (Java deep copy mainly includes custom clone and serialization)

4. Builder model

The builder pattern is a design pattern that is used more often when building a more parameters and the construction steps can choose the combination. The role of director is dispensable. This role is to avoid the caller from building the process. However, sometimes the construction process will inevitably be customized by the caller.

5. Adapter mode

The purpose of the adapter is to make an adaptation to the original type, so that other classes that cannot be called directly can call.

I wonder if the third-party direct call can’t work here? There may be a situation where you can’t change the code of a third party directly, or you want to decouple the code on both sides.

There are two modes of adapter: inheriting the adapter or having a member of the adapter.

In fact, after looking at some source codes, the most commonly used way of adapter is as follows: load all defined adapters, different callers find their own adapters in all adapters, and then execute a method in the adapter. The method has different implementations for different callers, and achieves the principle of opening and closing.

6. Bridging mode

If there are more than two dimensions of change, you can choose the bridging mode. Note that the change of the two dimensions is not the place of the two changes. For example, if there are men and women and the age is old, middle and young, those who can be combined in pairs belong to different dimensions.

In fact, at the beginning, I didn’t understand what separation of abstract part and implementation part is. Later, I thought about it. Maybe I read it wrong. Instead of separating from implementation part, it should be separated from implementation and part.

That is to say, the change of another dimension is separated. At first, I didn’t understand why an abstract interface is. After a careful look at the code, I found that the reason is that you can’t use set to combine interface classes without abstract classes. Ha ha, of course, the two abstract classes are OK.

7. Decorator mode

Decorator pattern mainly solves the problem that excessive inheritance leads to code maintenance difficulty. First of all, this inheritance belongs to the inheritance of extended functions. Subclass inheritance extends the functions of the parent class, such as the parent class of a pen. The subclass is pen, brush, pencil, etc., which are completely independent of each other and can not be used at all.

Why can we solve this problem? From the decorator mode, we can see that no matter how many subclasses there are, we only need to inherit a parent class one by one. No matter how many subclasses there are, it is possible to use inheritance. The most important thing is that the decorator mode allows users to combine and achieve various extension functions. In addition, inheritance requires extending the inheritance class.

Decorators belong to a combination, but the members used for composition are the same interface parent class. These operations are similar to the bridging mode in the upper floor, such as the pairwise combination of one dimension and the combination of multiple dimensions

8. Combination mode

Composition mode is similar to a leaf node structure, the scene is relatively simple.

9. Appearance mode

Facade, appearance mode is to provide a set of simple interface for the originally complex subsystem, which is similar to the adapter mode. However, the adapter mode is more suitable to make the classes that can not be called be called to be able to be called. Both the caller and the callee may not be modifiable, and the facade mode is to make it easier for the client to call.

10. Xiangyuan mode

All kinds of constant pools and thread pools use the sharing mode, which mainly reuses an object to avoid wasting performance by repeatedly creating. The sharing mode needs to pay attention to the internal and external states. The internal state can be shared and the external state will change.

11. Agency mode

Proxy mode used java all know, nothing to say. It mainly includes static proxy and dynamic proxy. Static proxy is to wrap the code to be proxied when writing code. Dynamic proxy is the agent conducted at runtime, which is divided into interface proxy and cglib method proxy.

12. Template mode

The template method is used for some life cycle functions and hooks. The general process has been written in the parent class. Different operations are implemented by covering several specific methods.

13. Command mode

Command callers, commands, and command receivers constitute the command mode. In short, command callers call commands, and commands internally call command receivers. This is a bit similar to the adapter pattern and the facade pattern. The adapter adapts two existing classes. The appearance mode is to simplify the interface, but what about the command mode? Why not directly command the caller to call the receiver? There is a specific scenario in the command mode, which is to record the log fallback. In addition, it can make a command queue and combine commands. The actions of this queue can be combined with each other. There is also the decoupling of command callers and command receivers. And just imagine, the command mode is like a remote control. I now have a remote control, and the key of the remote control is fixed. At this time, I can replace the command of the button to perform different operations.


14. Visitor mode

In order to solve the demand of new methods for object operation in a data structure class, the new method needs to add code in the data structure class, which does not conform to the open and close principle. The visitor mode puts the new method into the visitor class, which can be converted into adding different visitor classes. The visitor pattern can also have a feature, that is, the visitor visitor’s methods for accessing different objects are overloaded methods, and the parameters are different implementation classes of the parent class. Of course, this violates the dependency inversion. Therefore, one of the advantages of this kind of visitor is that it does not need to judge by pushing ifelse, but automatically infers the corresponding method through type. This more suitable scenario is in a traversal. Visitors mainly extend the methods of the original class, or extract the irrelevant behaviors from the original class.

15. Iterator pattern

Iterator pattern is also a common pattern in Java, so I won’t go into details.

16. Observer model

I think that the application scenario of observer mode is relatively simple, mainly a publish subscribe mode. In Java, there is a class called observable that implements the observer pattern well.

17. Intermediary model

The mediator model feels like a pattern designed to implement Dimitar’s law. It is to solve the complex call relationship between various types. Similar to the appearance pattern, the difference is that the mediation mode is mainly used to solve the mutual call between classes, and the appearance mode is to provide a unified external interface for multiple complex classes.

18. Memorandum model

Used to record the state of an object and can be used to fallback to one of the States

19. Interpreter mode

A design pattern that can be used to parse syntax or expressions

20. State mode

The state is inside the object, and the behavior is determined by the state

21. Strategic model

The policy pattern is suitable for some objects with similar behaviors. Through the member variables of the parent class, the subclasses can be converted to each other

22. Responsibility chain model

Java directly refers to the filter chain of spring MVC



The above are my personal views after learning the design mode, some places are also half understood, I hope to see more blog discussion!