Design Pattern final blow
About this article
The design pattern is an essential knowledge for every object-oriented developer. It is an experience of object-oriented design. However, the design pattern is a fuzzy technique for engineers. because he does not have strict mathematical analysis and proof, it is a reasonable experience tested by practice and is especially difficult for beginners to understand. I was also confused. With the increase in engineering practice, I became more and more clear about the design model. So I want to write a final summary and write down my understanding of the design model in a concise manner, in the future, we will not be entangled in this, but also provide reference, correction, and communication for other friends.
Basic Design Patterns
Although the design pattern is the product of practice, it follows some common principles in the initial design. The author believes that the design pattern is obviously based on three principles, or the overall goal:
Open and closed principle: Allow new extension systems, but refuse to modify system isolation complexity and changes: use various means to aggregate complexity into a relatively concentrated class or module, it is not reusable in all aspects of the system: in fact, this is also the title of the classic book of 23 design patterns, although no one can design a module that can be reused at any time under any circumstances, the design model strives to achieve better reusability.
Some may ask why there are no five object-oriented design principles? What is a single responsibility, Liskov replacement, and so on. In fact, all these principles are embodied in the design pattern, but these principles are not the core but the means to achieve the core things. For example, to achieve reusability, the single responsibility principle and interface isolation principle may be used for reference.
In fact, if we observe it carefully, we will find that the discussion of the advantages and disadvantages of the classic book after each pattern embodies the three principles above.
Design Pattern comment
If you have read the design patterns carefully, you will find that some design patterns are similar in the class diagrams, and some are even identical. The difference is only the responsibility of the scenario and class. First, we will discuss the summarized three similar structures.
Sibling dependent
There are two types of specific classes (non-Abstract) A and B, where A depends on B to implement certain functions, and A and B can implement common interfaces, you can also implement their own interfaces.
The Adaptor mode and Proxy mode have similar structures above.
The class structure of the Adaptor mode is identical. A is the adapter, and B is an implementation of the adapted interface (Adaptee ). This mode is very common, and the motivation is that the Client often needs a specific interface IA, while the existing interface IB is not required by the Client. The direct idea is to allow B to implement the interface IA again and implement the method in IA. In this brute-force solution, adapter A is redundant. The following uses the three principles mentioned above to analyze why the adapter is better than this simple brute force solution.
First, the open and closed principle requires that classes be extended when changes occur, rather than modifying classes. In a simple solution, we have to modify B's code to implement the IA interface.
Secondly, good design should isolate complexity and changes. In a simple solution, if another client, Client2, needs another interface IC, then B has to implement the IC. to the extreme, what if I have 100 clients, each of which must have its own Interface format? In this way, Class B cannot be directly viewed.
The final criterion requires that the module be reusable as much as possible. So, we have implemented 100 different interfaces, and can the specific function defined by the interface be similar to that defined by B?
After analysis, I think I have decided to compete. Finally, the Adaptor mode is mentioned in many books that refer to an inheritance-based mode, that is, adapter A no longer depends on B, but inherits B. For such a form, I just want to say that a combination is better than inheritance.
The class structure of the Proxy mode is simpler. The IA and IB interfaces implement one, that is, A and B Implement the same interface ICommon, A is the Proxy class, and B is the Proxy class. The main motivation of this mode is to perform some additional functions or operations on the basis of the specific class to be proxy, but the interface exposed externally remains unchanged.
In Java, the proxy mode described in the above class diagram actually becomes a static proxy, while Java supports a more flexible dynamic proxy mode. As shown in the class diagram, the only difference between dynamic proxy mode is that proxy class A is no longer directly dependent on the proxy class B. Through the Java reflection mechanism, class A can control the method of the class to be proxy to be called at any time, instead of having to relate to the class or method that it actually proxies, so that Class A can focus more on its own additional proxy operations, the direct dependency between A and B is also eliminated.
Dynamic proxy is more powerful. Imagine that if you want to delegate 100 classes or 100 methods, you have to create 100 static proxy classes accordingly, the additional operations implemented by these static proxy classes may be the same. Dynamic proxy is widely used in frameworks and underlying class libraries. For example, various SQL templates in spring are dynamic proxies. For example, when Spring integrates Mybatis, SqlSessionTemplate dynamically proxies SqlSession in Mybatis. However, in a simple scenario, the use of static proxy is more concise, and there is no performance loss caused by reflection. Of course, I have nothing to say about using dynamic proxy in any situation because I look awesome.
Hierarchical Structure
This type of design pattern presents a certain hierarchical relationship in the object structure. These patterns include Composite, Decorator, and Interpreter. The typical class diagram is as follows:
The class diagram above is actually a complete description of the Composite mode. A Composite object can combine one or more Component, which can be either a Composite instance or a Leaf instance, for a Composite instance, a tree-level nested structure is formed.
In software development, such a structure can be seen everywhere. In java graphical interface development, controls such as Button and ComboBox correspond to Leaf, while container controls such as widgets and Group correspond to Composite. container controls can be nested and contain Leaf controls, to design a variety of complex interface elements, in addition, the JSON and XML file processing libraries in Java also need to construct such a hierarchical nested structure when expressing the relevant structure.
The Interpreter mode can be considered to be a specific application of the Composite mode in the Syntax Parsing scenario. Therefore, I personally think that the Interpreter mode does not have to be separately listed as a design mode. In Interpreter mode, Leaf is the terminator of a syntax, while Composite is a non-Terminator. Non-terminator can be nested. Therefore, a hierarchical syntax tree can be formed between objects.
As for the Decorator mode, it can be considered a variant of the Composite mode with certain limitations. In the class diagram, In the Decorator mode, the Decorator is Composite, while the Leaf class is the decorated Target. The only restriction is that the Decorator Can only combine one Component interface instance, while in Composite, composite can have multiple Component interface instance members. This eventually leads to different structures between objects. In Composite mode, objects can form a nested tree-level structure, in the Decorator mode, objects can only form one single-chain table (of course, they can also be considered as a special tree ).
Some developers also refer to the Decorator mode as the Wrapper mode, which adds additional functions to an interface. The Proxy mode mentioned above also adds additional operations. What is the difference between the two? To analyze the difference, you need to start from the class graph Source: Decorator depends on abstract interfaces and provides additional implementation for abstract interfaces, regardless of the specific classes to be decorated; proxy is not an abstract interface, but a concrete method of a specific class. Therefore, the key to choosing Decorator or Proxy in an application depends on what you want to Proxy or wrap. Is it an abstract type, an interface, or a specific class?
Common combination
The general combination type is relatively simple in the class structure. The customer class combines the implementation of an interface, and the interface has several implementations. According to different implementations, the customer class can flexibly obtain different behaviors, in fact, this is the simplest demonstration of object-oriented polymorphism:
This type of design pattern includes the State pattern, the Strategy pattern, and the Flyweight pattern.
The State mode and Strategy Mode are exactly the same in the class diagram. The main difference is the use case. The State mode encapsulates each State as a specific class, the Strategy Mode encapsulates each algorithm implementation into a specific class. This explanation is correct, but it is a little simple. If you perform further observation and analysis, the two modes are actually not exactly the same in the class graph structure and Class Interaction details.
In State mode, after each State object completes the action method, it returns another State object to indicate the transition between states. That is to say, ConcreteA and ConcreteB are dependent on interfaces, this dependency is not provided in the classic works of this design model. In addition, in the request method of the Context object, every time the action Method of the interface is called, The State object held by the Context object must be updated to indicate a change in its status.
In contrast, the Strategy Mode is simpler. In ConcreteA and ConcreteB, action methods generally do not produce parent interfaces or dependencies between them. They are just an implementation of algorithms. The Interface instances held in the Context object are generally set through dependency injection before running, and will not change during running.
In addition, do not be intimidated by terms such as strategies and algorithms in the Strategy Mode. This mode is also everywhere in the Java language library, for example, we usually sort Collections with custom comparator sets. sort, and the method File that filters and lists sub-files in the Java IO library. list (FilenameFilter filter) and File. listFiles (FileFilter filter) and a bunch of static methods in the CollectionUtils class in the Apache Collection library. I personally think that the current popular function programming practices of passing functions as parameters are essentially the Strategy Mode.
Some beginners may ask, what are the advantages of using these two modes to create many classes? Take the State mode for example. If this mode is not used, how can we convert different states inside an object? It is nothing more than defining a bunch of enumerated values, and then if-else is full of flying, or the various processing functions in the switch-case, it is very disgusting (if you are a C programmer, if-else looks comfortable, I can't help it ). Of course, you cannot convince others of the advantages of these models. What are the advantages of these two models?
Flyweight is an application of this structure in the Shared Pool, except that Context becomes Factory and holds a Map to store multiple Interface implementation objects. Factory provides the get method to obtain the specified instance object. If the object does not exist, Factory initializes an appropriate Interface implementation.
An interface and an abstract class
In essence, the State mode and Strategy Mode mentioned above are implemented only through the polymorphism commonly supported by object-oriented language. In fact, there are simpler modes.
Define an interface method clone and create a class to implement it. It is the prototype mode. The structure is simple. Although the structure is simple, the semantics is not simple. You need to create another object that is exactly the same as the object. If the object is complex, you need to make a trade-off between deep copy and shallow copy. Java's Object itself supports this mode. You only need to rewrite the clone method, but it is as simple as rewriting the equals method of the Object. However, if you haven't read the variable-tive Java, how many people can write it out without leaking?
Define an abstract class, define some abstract methods and non-abstract methods, and then create a class to inherit this abstract class to implement these abstract methods. This is the Template mode. The thought behind the seemingly simple Template mode is worth chewing. It tries to simplify the implementation of complex functions or processes into the implementation of several small functions, this reduces the difficulty of complex functions or process implementers.
The Template mode is everywhere in the Java language library: If you want to implement a linked List of your own, you will implement the Java List from the beginning Interface? To do this, you need to implement more than 20 methods, including size, get, add, and contains. The simpler method is to directly inherit from Java's javasactlist Abstract class. In this way, you only need to implement five methods: size, get, set, add, and remove. Other methods can be implemented by default through the five methods you have implemented, abstractList is ready for you. You only need to inherit it. The other example is from JavaEE. In fact, Servlet itself is an application in the Template mode. Imagine how you handle Get and Post requests? Inherit an HttpServlet, and then rewrite the doGet and doPost methods. You don't have to worry about what the Get and Post processes are like, the doGet and doPost methods you write are only a link in the complicated processing process of Servlet containers.
Service creation
The creation mode is a separate design mode, which focuses on Object creation and is relatively easy to understand. Some developers who are new to the design pattern do not agree with it, because new can't do everything right? New is indeed the most powerful way to create objects, and is even the only way in some languages (Java. However, the biggest defect of new is that it is closely bound to a specific type. In a large system, the type structure is complex, there are many types, and the specific types that are constantly evolving often become complex points, in this way, new is closely coupled with this complexity. The guidelines in Chapter 1 require us to isolate complexity and changes. Therefore, it is necessary to encapsulate new in various design patterns of the creation model.
The Singleton mode is an important design model. In the real world, many scenarios are singleton. In other design models, the singleton mode is often supported by Singleton. Java does not provide direct support for the singleton mode. The common implementation is to create a static member of the class range using the Java class lifecycle, because the class is always unique during Java loading, therefore, this static member is unique. Then, you need to close the class constructor of the static member and provide the static get method to obtain the single-instance Member.
It should be noted that if you delay the instantiation of static member variables to get, you need to consider the thread security issues under multi-thread, simply add synchronization before the static get method. If you are using performance control, you can also use "double lock check usage" to optimize it.
The Singleton mode is now directly supported by emerging languages. For example, scala provides an associated object mechanism that allows you to directly create a singleton object. Although indirectly supported by Java, there is still a question: if the class lifecycle and static scope are not used, how can we implement the singleton mode?
In Builder mode, an object is encapsulated into a Builder instance object based on previous settings. The original motivation of the Builder mode is to simplify the construction process of a complex object, but I do not fully agree with this statement, because sometimes a complex object needs to set a dozen fields before use, after the Builder object is encapsulated, you still need to set these fields, and the workload is not reduced.
I think the main motivation of the Builder mode is to make the responsibilities of complex objects more uniform. If a complex object has more than 10 set methods, the real Service methods are only two or three, it's hard for you to figure out what this object is. Therefore, put the initialization and setting process of a Service object into the Builder object. Once the Service object is obtained, it will be immutable, but it will only provide business services, so that the Service object will be much simpler, its responsibilities will also be more specific.
Two typical applications of the Builder mode are provided: one is the creation of LoadingCache objects in the Google Guava library, and the other is the creation of HttpClient objects in Apache HttpComponents 4.3 or later versions.
The factory method mode and the abstract factory mode both contain the word factory, so we will discuss them together. We often use the factory method mode, but this mode has some nuances. First, let's take a look at how the original document describes this mode:
The motivation of the original author is to use the factory method to achieve two objectives:
Encapsulate the creation of Product instance objects. Removing the dependency of Product users on specific Product types delays the creation of specific Product subclass to the corresponding sub-factory classes, let the common operations of each Product subclass be mentioned in the method of the parent factory class (the AnOperation method of the Creator)
However, we usually see that the Factory method mode is not in this form, but more is to encapsulate the creation of the Product subclass object into the static method of the Factory class, the Factory itself has no hierarchical relationship. Taking the commonly used thread executor in the Java concurrent library as an example, the class diagram is as follows:
The Executors of the factory class do not have an inherited hierarchy, but create the objects implemented by each ExecutorService as their own static method. In this way, the two motivations of the original author only implement the first one, this is a simplified version of the original factory method model. For the two factory methods, it is clear that the latter is more concise, but it lacks some advantages. However, if you do not need these advantages, it is more wise to choose a concise solution, the so-called existence is reasonable.
The abstract Factory mode is similar to the original Factory method mode. both Product and Factory have inheritance hierarchies, such:
The biggest difference between Abstract Factory and original factory methods is from Product analysis. In the abstract factory model, Product has multiple relatively independent hierarchical systems, such as AbstractProductA and AbstractProductB. The most critical point is that specific products in different Product systems have a certain relationship, for example, ProductA2 and ProductB2 may have some relationship. For example, both products are Simple or both products come from the same manufacturer. In this way, to better reflect this relationship, we encapsulate the acquisition methods of the two products into the same abstract factory class implementation, that is, ConcreteFactory1.
So the question is, what should we do if there is no relationship between AbstractProductA and AbstractProductB subclass? Can we still use the abstract factory model? In this case, it is obviously inappropriate to use the abstract factory mode to hard-plug two irrelevant Product instances into the same factory instance. This solution is simple and violent: use the factory method for AbstractProductA and AbstractProductB respectively!
Responsibility Refining
A single responsibility is an important means to achieve the three goals in Chapter 1. A single responsibility makes the granularity of each class smaller and easier to reuse; one category and one responsibility do not affect each other's changes and complexity. A single responsibility also reduces the cost of modification. Based on a single responsibility, the original author designed several design modes to describe them in Bridge, Iterator, responsibility chain, and visitor modes.
According to the official statement, the Bridge mode is used to separate interfaces and implementations. Interfaces and implementations are tightly coupled, but when a subinterface appears on the interface, the situation becomes worse, just like this:
Originally, RoleA has two implementations: RoleA1 and RoleA2. Now there is another sub-interface RoleB, which leads to the implementation of RoleB, the two implementations of the method inherited by RoleB need to be re-written, and these four disgusting implementation classes appear.
A problem arises immediately: in the Java language library, such structures are everywhere. For example, the Interface Collection has a subinterface List, and an abstract template named AbstractList under the List, there are many specific List implementations at the bottom layer. Why does the Java Collection library look so elegant and there is no problem at all?
To answer this question, you have to go back to the single responsibility topic. The root cause of the problem in the above class graph is that RoleA and RoleB do not have a very close business inheritance relationship, or they are two irrelevant roles. We know that inheritance is the most coupled method. When RoleB and RoleA are less closely related, inheritance will lead to problems, at this time, RoleB is reluctant to inherit the method interface method that has nothing to do with RoleA. Then, in subclass implementation, the tragedy happened. The methods and operate methods all need their own implementations, and finally they have to be combined to form four disgusting implementation classes. In fact, these four implementation classes have different responsibilities.
In contrast, in the Java Collection library, List and Collection are closely related to "is-a". The interface methods inherited by List from the Collection interface, together with their own methods, form an inseparable whole, the specific implementation class does not fully understand which methods belong to its grandfather Collection, and of course it will not happen.
Since the problem lies in RoleA and RoleB, you have to find the solution from these two interfaces. Since RoleA has a relationship with RoleB, but it is not close to that level, it should replace inheritance with a slightly weaker combination, that is, RoleB combines RoleA instead of inheriting RoleA. In this way, RoleB's implementation class does not need to implement the method, because RoleB has no method at all. The implementation classes of RoleA and RoleB only need to implement their own interface methods, the class diagram is as follows:
Does this class chart look like the Bridge pattern in the original book of design patterns? RoleB in the original book is the so-called Abstract abstraction, while RoleA is the so-called Implementation. The Bridge Mode of the original book is to separate abstraction and Implementation in the class system, so that they can change each other. In my opinion, the Bridge Mode separates different responsibilities in the inheritance system and changes them separately. This is a more general and essential expression of the Bridge mode.
The responsibility chain mode is a typical mode in data stream processing scenarios. Each object in the responsibility chain holds the next object reference. After the data is processed, the data is sent to the next object for processing. This is a simple and clear separation of duties. An object is responsible for one responsibility, and there is a sequence of responsibilities. The responsibility objects form a chain structure.
Do you still remember a design pattern that may have a chained object structure described earlier? Right, that is, the decoration mode. Each decoration object in the decoration mode also has a chain structure. The difference is that the decoration mode is not for data processing, instead, each modifier object is used to enhance or modify the function of the next modifier object.
JavaEE includes a typical application of the responsibility chain model, that is, Filter. You can. configure multiple Filter objects in xml and specify the relationship. Each Filter object calls chain after processing the request. doNext, let the next Filter object process, know that the request arrives at the Servlet instance.
The Iterator mode does not need to be explained. Java Collection class libraries such as List, Set, Map and other interfaces support this mode. This mode is easy to understand because it has a single application scenario and clear responsibilities. It separates the iterative operations of the Set, defines it as an Iterator interface, and defines the call specifications of each method in the interface, for example, iterator. next and iterator. iterator must be called before and after the remove operation. hasNext method. Someone may ask, I can iterate the List without Iterator. When talking about this, I must mention the significance of the two most important aspects of the Iterator:
Provide consistent methods for various Set iterations: You can certainly use for loop iteration List, but how to use for loop iteration Set and Map? Allows destructive operations on a set in an iteration: the so-called destructive operation is generally to delete an element. You can also determine and delete the List element of the current index in the for loop, however, you need to calculate the relationship between the iteration variable I and the length of the deleted List element, and be careful when the index subscript crosses the border or the element is missing.
Next, let's talk about the most difficult-to-understand Visitor mode. First, let's look at this mode from the high-level perspective. The first two modes separate different data processing and iteration responsibilities. What are the responsibilities of the Visitor mode? Visitor separates the "unreliable" changes to a complex object.
The object-oriented model focuses on encapsulation, which encapsulates data and operations on data, in the Visitor mode, modifications to a complex object must be removed and encapsulated into another Visitor object. Does this damage the encapsulation of object-oriented objects? Yes, the Visitor pattern does undermine encapsulation. This is the shortcoming of the Visitor pattern clearly stated in the design pattern book, but this destruction has to be done, the reason is that the changes written in the previous section are "unreliable ".
To explain "unreliable", suppose you have obtained a lot of data from the database and built a StockModel object to indicate the stock market. This object structure is complex enough, it contains many stock attributes and hierarchical structures. You plan to provide this object to the JSP display of the presentation layer. At this time, the "unreliable" operation is reflected in the following two points:
The operation was Special: One day, the product manager suddenly asked you to temporarily adjust a field in StockModel. For various reasons, you could not modify the data in the database, so you had to complete it through code. Operations increase frequently: Once your StockModel is targeted by the product manager, your special handling of it will be endless.
This unreliable operation is indeed closely related to StockModel, but if you use these methods as the StockModel method, the problem arises. Although these operations are related to StockModel, they are all special operations that only the product manager can understand. It looks strange to regard these methods as the public method of StockModel. On the other hand, the frequent increase in special processing increases the number of StockModel methods and code. A bad class with thousands or even tens of thousands of lines of code is born in minutes.
The solution is the Visitor mode: Define a Visitor interface, and the interface method is a visit (StockModel model). Each special process creates a Visitor implementation, write the special processing process to the visit method to separate special processing responsibilities. In this way, a new special processing does not need to modify the StockModel, but creates a new Visitor implementation, it perfectly complies with the open-closed principle, and the ideas and methods are so simple.
So where is the most difficult to understand the Visitor model? Let's take a look at the quasi-class diagram of Visitor in the design mode:
Programming field, performance, functional programming. Even as your experience increases, you can try to summarize the new model. In a word, you must stay old and learn Old.
The Command mode and Memento mode that are not mentioned in this article are common in GUI software development. The author rarely involves them in his own Web field, so I am not afraid to create them. I also hope that you can add more in the industry, the right when the author here.