common design patterns

Design Principles:

Design principles are the most important ideas, and the so-called design patterns are just the application of design principles.

1. Encapsulate changes: separate the places in the code that may need to be changed, and don’t mix them with code that doesn’t need to be changed.

2, to rely on abstraction, do not rely on concrete classes. (Oriented to abstract programming

3. Use combination more and less inheritance.

4. Try not to call across layers. The upper layer should call the lower layer, and don't let the lower layer call the upper layer.

5. Open for extension and closed for modification.

6. A class should have only one reason for change.

Specific design patterns:

1. Strategy mode: Encapsulate a family of algorithms so that they can be replaced with each other.

Define a unified interface for a family of algorithms, and then let each member of the family implement this interface. The client side holds the unified interface of the family rather than the concrete implementation, so that it can be replaced with each other within the family.

For example, for a calculator, first define a calculation interface, which has the implementation of four specific calculations of addition, subtraction, multiplication and division. When calculating, we decide which specific calculation class to use according to the operation symbol. Usually the strategy pattern is used with a simple factory (remember to encapsulate the change, where getting the specific calculation class is a change point, the rest are unchanged).

2. Factory methods and abstract factories

A simple factory just encapsulates the point of change of producing an object.

Factory method: defines an interface for creating objects, but it is up to the subclass to decide which class to instantiate.

The code structure diagram is the same as the strategy pattern, but the roles of the two are different. Strategies are for encapsulating algorithms, and factory methods are for instantiating different objects. And the factory method does not necessarily need to define a separate new interface, just like the template method, the interface can be defined in the parent class, and the subclass can complete the specific implementation.

Abstract Factory: Provides an interface for creating families of related or dependent objects.

The abstract factory is established to create an object family, that is to say, there is some kind of association between the objects produced in the implementation class of the same abstract factory.

A typical example is computer matching: we know that there is a matching relationship between the cpu slot of the motherboard and the pins of the cpu. At this time, we use an abstract factory method to ensure that the obtained motherboard and cpu are matched.

3. Observer pattern: defines a one-to-many dependency between objects, so that when an object changes state, all its dependents will be notified and automatically updated.

This mode is easy to understand. The specific implementation is to define an observer interface and an observer interface. When the observer is registered as the observer, the observer holds the observer object. When the observer changes, the observers are notified one by one. .

4. Decorator pattern: dynamically attach responsibilities to objects.

When it comes to decorator mode, we can't help but mention java's io. Everyone who uses io knows that one by one, sometimes it will be covered with many layers. This is the decorator mode. The implementation of the decorator pattern is actually quite simple. First define a unified interface, and then implement a basic underlying implementation, followed by the decorator. The decorator also implements the unified interface and holds a reference to the interface (interface-oriented programming). The decorator calls before or after The interface of the object held, so that you can use the decorator to replace the specific implementation class to complete additional functional expansion.

5. Singleton pattern: Ensure that a class has an instance and provide a global access point.

The singleton mode is also relatively easy to understand. When using it, you should mainly pay attention to the problem of thread synchronization. Its more common implementation is to double null judgment, and add the synchronization lock to the null judgment of the second layer. There is also a static inner class to obtain an instance of a singleton. It is said that there is another kind of implementation using enumeration. I have not tried this, but I will try it when I have time.

6. Command mode: encapsulate the request into a command interface. The command interface holds the object interface that actually executes the action or a series of actions (these interfaces are not uniform). When the command interface is implemented, the implementation of each actual execution object is actually called. .

In fact, the command pattern is to insert another layer between the caller and the callee to realize the decoupling between the caller and the callee. This is done because the callee is not a unified interface (the example in the book is that there are lights, air conditioners, refrigerators, etc. and other TVs are messed up), if you do not join the command mode, then every time you replace the callee It is too expensive to change the caller's code. After adding the command mode, changing the callee only needs to call the caller's setCommand method to reset the new command.

7. Adapter mode: Convert the interface of a class into another interface expected by the client.

Now there are two interfaces, A and B. We have the implementation of the B interface, but the client calls the method of the A interface. At this time, we cannot modify the client's interface. At the same time, we don't want to rewrite the implementation of the A interface. We can Use an adapter to solve this problem. The so-called adapter C is to let C implement interface A and hold a reference to interface B. When calling the method of interface A of C, it is actually calling the specific implementation of interface B.

8. Appearance mode: Define a unified interface to access a group of interfaces in the subsystem.

As the name implies, it is to encapsulate a group of related interfaces into an external interface, which is convenient for external calls. Typically used in scenarios where an external function requires multi-step subsystem functions.

9. Template method pattern: define the skeleton of an algorithm in a method, and defer some steps to subclasses. Template methods allow subclasses to redefine certain steps in an algorithm without changing the structure of the algorithm.

This is the mode I use more often. The essence of this pattern is to encapsulate the same process and provide default implementations for some common subprocesses, leaving specific subprocesses for each subclass to implement. When we usually connect the interfaces of other systems, the process is nothing more than assembling parameters, obtaining urls, sending requests, and parsing responses. These sub-processes can be encapsulated in a method of a parent class, so that each subclass can implement specific subclasses. process.

10. Iterator pattern: Provides a way to sequentially access elements in an aggregate object without exposing its internal representation.

This mode can be seen in the collection class of java. All collection classes implement the Iteratorable interface, so that we can read all collection classes uniformly regardless of which collection class it is and its internal data structure. what is.

11. Composition mode: Allows you to group objects into a tree structure to represent a "whole/part" hierarchy. Composition enables clients to work with individual objects and groups of objects in a consistent manner.

As the name suggests, the combination mode is to combine objects into a tree structure. The specific implementation method is that the interface holds a collection of itself as the child node of the node. There are two representations here. One is that the branch node and the leaf node implement the same interface, that is, the leaf node also has methods for adding child nodes and obtaining child nodes, but these two methods are directly thrown in the leaf node. Exception without specific implementation, this way allows clients to handle branch nodes and leaf nodes in the same way. The other is that the leaf node and the branch node implement different interfaces. From the interface, the two are distinguished, which avoids the operation of obtaining child nodes on the leaf node, but in this case, the client needs to know the two interfaces. Which method to use depends on your needs. At the same time, the interior of the combination mode is also a data structure, so the general combination mode will be used together with the iterator mode.

12. State Pattern: Allows an object to change its behavior when its internal state changes.

The structure diagram of the state pattern is basically the same as the structure diagram of the strategy pattern, but the purpose of the two is different. The strategy pattern is the replacement of individual behaviors, and the state pattern is that each state has to implement all the behaviors of the main class. For example, a duck has three states: full, normal, and hungry; there are three behaviors: flying, calling, and running; each behavior behaves differently in each state, which means that each state must implement the duck's Three behaviors, this is the state pattern. The specific implementation method is that the main class holds a current state, and the specific behavior of the main class actually calls the behavior of the current state. Whenever a certain condition is reached, the current state of the main class will switch to other states to change the behavior of the main class. the goal of.

13. Proxy mode: Provide a stand-in or placeholder for another object to control access to this object.

This pattern is very similar to the Decorator pattern, but again, the purpose of the two is different. The purpose of the decorator pattern is to change the behavior of the decorated class, while the main purpose of the proxy pattern is to control access to objects. Some people may say that the same structure is the same pattern. In fact, it is not. The problem you want to solve determines which mode you use, even if they have the same structure, it must be clear.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324503693&siteId=291194637