1. I have recognized so many design patterns. I have heard of the design pattern from students who have been familiar with java for a short time. However, due to limited capabilities, I have never dared to touch it. Now I have the honor to know all of them.
2. Start with the design theory. I didn't think much about design before I came into contact with the design model. When I saw the problem, I immediately solved it. I didn't think about how to design it better, but how to make it more optimized and beautiful.
3. start to consider the scalability of the system.
4. start to think of the design pattern that will apply to this scenario after a problem occurs.
5. Have a deeper understanding of object-oriented.
You are not smart, not wise, not that kind of genius. All epiphany is limited !!! There are too many gossips. first look at the following two pictures.
Relationship between design patterns:
Overview of design patterns:
I. Design Principles 1. Single responsibility principles
A class has only one reason for its change. There should be only one responsibility. Every responsibility is a changing axis. If a class has more than one responsibility, these responsibilities are coupled. This leads to a fragile design. When a responsibility changes, other responsibilities may be affected. In addition, coupling of multiple responsibilities will affect reusability. For example, you need to separate the logic from the interface. From: Baidu encyclopedia
2. Open Close Principle)
The principle of opening/closing is to sayOpen to extension and disable Modification. When the program needs to be expanded, you cannot modify the original code to achieve a hot swapping effect. So in a word, it is easy to maintain and upgrade the program to make it more scalable. To achieve this, we need to use interfaces and abstract classes. We will mention this in the specific design.
3. Liskov Substitution Principle)
Liskov Substitution Principle LSP is one of the basic principles of object-oriented design. In the Rys replacement principle, subclasses can certainly appear where any base class can appear. LSP is the cornerstone of inheritance reuse. Only when the primary class can replace the base class and the functions of the software unit are not affected can the base class be reused, the category class can also add new behaviors based on the base class. The Li's replacement principle is a supplement to the "open-closed" principle. The key step for implementing the "open-close" principle is abstraction. The inheritance relationship between the base class and sub-classes is the specific implementation of abstraction. Therefore, the Li's replacement principle is the standard for the specific steps to implement abstraction. From: Baidu encyclopedia
4. Dependence Inversion Principle)
The Dependence Inversion Principle is dependent on abstraction, not specific. Simply put, we need to program the abstraction rather than the implementation, which reduces the coupling between the customer and the implementation module.
The key to achieving the principle of open/closed is abstraction, and specific implementation is exported from abstraction. If the principle of open/closed is the goal of object-oriented design, the principle of dependency reversal is the main means of object-oriented design. From: Baidu encyclopedia
5. Interface Segregation Principle)
This principle means that using multiple isolated interfaces is better than using a single interface. We can see from this that the design mode is a software design idea, starting from the large-scale software architecture, for the convenience of upgrading and maintenance. So it appears many times above: reducing dependencies and reducing coupling.
6. Composite Reuse Principle)
The principle of merging and reusing is to use existing objects in a new object through associations (including composite and aggregation relationships) to make them part of the new object; new objects reuse their existing functions by calling existing methods by Delegate. To put it simply, use combination/aggregation as much as possible, and use less inheritance.
7. Demeter Principle)
What is the principle of least understanding? That is to say, an entity should interact with other entities as little as possible so that the system function modules are relatively independent. That is to say, a software entity should interact with other entities as little as possible. In this way, when a module is modified, it will affect other modules as little as possible, and expansion will be relatively easy, which is a limitation on communication between software entities, it requires limiting the width and depth of communication between software entities.
Ii. Creation Mode
In software engineering, the creation mode is the design mode for processing object creation, and tries to create an object in an appropriate way according to the actual situation. The basic object creation method may cause design problems or increase the design complexity. The Creation Mode controls the creation of objects in some way to solve the problem.
The creation mode consists of two dominant ideas. One is to encapsulate the specific classes used by the system, and the other is to hide the creation and combination of the instances of these specific classes.
The creation mode is divided into object creation mode and class creation mode. The object Creation Mode processes the creation of objects, and the class Creation Mode processes the creation of classes. In details, the object Creation Mode delays the creation of a part of the object to another object, while the class Creation Mode delays the creation of its object to the subclass.
1. Abstract Factory)
The so-called abstract factory mode is an interface provided by her to create a family of related or dependent objects without explicitly specifying a specific class. It allows the client to use abstract interfaces to create a group of related products without having to relate to the specific products actually produced. In this way, the customer can be decoupled from a specific product. Its advantage is that it isolates the generation of specific classes, so that the client does not need to know what is created, but the disadvantage is that it is troublesome to add new behaviors, because when you add a new product object, you need to change the interface and all its subclasses. Its UML structure is as follows:
Participants:
AbstractFactory: Abstract Factory. The abstract factory defines an interface, which must be implemented by all specific factories. This interface contains a set of methods used to produce products.
ConcreteFactory: specific factory. The specific factory is used to produce different product families. To create a product, you only need to use one of the factories and do not need to instantiate any product objects.
AbstractProduct: Abstract product. This is a product family, and each specific factory can produce a whole group of products.
Product: specific Product.
2. Builder Mode)
The builder mode separates the construction and representation of a complex object, so that different representations can be created during the same construction process. The internal structure of product objects is complicated.
The builder mode encapsulates the construction process of complex products into different methods, so that the creation process is very clear and allows us to control the creation process of complex product objects more accurately, at the same time, it isolates the creation and use of complex product objects so that different products can be created in the same creation process. However, if the internal structure of a product is too complex, the entire system will become very large, which is not conducive to control. If there are large differences between several products, the builder mode is not applicable, after all, there are not many two products with the same points in the world, so their use scope is limited. Its UML structure:
Participants:
Builder: Abstract Builder. It declares the abstract interface specified for each part of a Product object.
ConcreteBuilder: Specific builder. Implements abstract interfaces to build and assemble components.
Director: conductor. Construct an object using the Builder interface. It is mainly used to create a complex object. It has two main functions: one is to isolate the production process of customers and objects, and the other is to control the production process of product objects.
Product: Product role. A specific product object.
3. Factory Method)
As the twin brother of the abstract factory mode, the factory method mode defines an interface for creating objects, but the subclass determines the class to be instantiated, that is, the factory method mode delays Instantiation to the subclass.
The factory method mode is very compliant with the "open and closed principle". To add a new product, we only need to add a specific product class and the corresponding factory, you do not need to modify the original system. In the factory method mode, you only need to know the specific factory of the production product, and do not need to know the product creation process or even the specific product class name. Although he well complies with the "open and closed principle", because two classes need to be added every time a new product is added, this will inevitably increase the complexity of the system. Its UML structure:
Participants:
Product: Abstract Product. All products must implement this common interface, so that the class of these products can reference this interface. Instead of a specific class.
ConcreteProduct: specific product.
Creator: Abstract Factory. It implements all product manipulation methods, but does not implement factory methods. All subclasses of the Creator must implement the factoryMethod () method.
ConcreteCreator: specific factory. The actual factory of the manufacturing product. It is responsible for creating one or more specific products. Only the ConcreteCreator class knows how to create these products.
4. Prototype)
Some objects in our applications may have complicated structures, but we need to use them frequently. If we create this object continuously, the system memory will be greatly reduced, in this case, we need to use the prototype mode to clone the complex and frequently used objects. Therefore, the prototype mode uses a prototype instance to specify the type of the object to be created, and creates a new object by copying the prototype.
It is mainly used when the cost of creating new objects is too high. Its main advantage is to simplify the process of creating new objects, improve efficiency, and provide a simplified creation structure in the prototype mode. UML structure diagram:
Participants:
Prototype: Abstract Prototype class. Declare the clone interface.
ConcretePrototype: prototype. Specific clone operations.
Client: Customer class. Let a prototype clone itself to get a new object.
5. Singleton)
Singleton mode is literally an instance. Therefore, it is defined to ensure that a class has only one instance and provides a global access point.
The Singleton mode has the following features:
1. There is only one instance.
2. Self-instantiation.
3. provides global access points.
Therefore, when only one instance object is required in the system or only one public access point is allowed in the system, the instance cannot be accessed through other access points except this public access point, you can use the singleton mode.
The main advantage of Singleton mode is to save system resources, improve system efficiency, and strictly control customers' access to it. It may be because there is only one instance in the system, which leads to excessive responsibilities of the singleton class, violating the "single responsibility principle", and having no abstract classes, therefore, it is difficult to expand. Its UML structure is very simple and there is only one class:
Participants:
Singleton: Singleton.
Iii. Structural Mode
The structural mode is mainly used to process the combination of classes or objects. It describes how to better combine classes or objects and solves the coupling problem between modules from the program structure. It mainly includes seven modes: adapter mode, Bridge Mode, combination mode, decoration mode, appearance mode, metadata mode, and proxy mode.
1. Adapter Mode)
In our applications, we may need to communicate with classes of two different interfaces. without modifying these two classes, we may need a middleware to complete the connection process. This middleware is the adapter. The so-called adapter mode is to convert an interface of a class into another interface that the customer expects. It allows the original two incompatible interfaces to be seamlessly connected.
The middleware adapter decouples the target class and the modifier, increasing the transparency and reusability of the class.
Participants:
Target: The Target abstract class.
Adapter: Adapter class. Wrap an Adaptee internally to convert the source interface to the target interface.
Adaptee: adaptor class. The class to be adapted.
Client: Customer class.
2. Bridge)
If a system can be classified from multiple perspectives and each category may change, what we need to do is to separate these multiple perspectives, this allows them to change independently and reduce coupling between them. This separation process uses the bridging mode. The so-called Bridge Mode isolates the abstract part and the implementation part so that they can change independently.
In the bridge mode, the inheritance relationship is converted into an association relationship, which encapsulates changes, completes decoupling, reduces the number of classes in the system, and reduces the amount of code.
Participants
Abstract action: abstract class.
Refinedmediaaction: extends the abstract class.
Implementor: Implements class interfaces.
ConcreteImplementor: Implementation class.
3. Composite)
The combination mode combines multiple objects to form a tree structure that represents the "Whole-part" structure hierarchy. It defines how to recursively combine container objects and leaf objects so that customers can perform consistent processing without distinction during use.
When using the combination mode, note that the leaf object and the combination object implement the same interface. This is why the combination mode can process leaf nodes and object nodes in the same way.
Although the combination mode can clearly define hierarchical complex objects and make it easier to add new components, this leads to more abstract system design, if the business rules of the system are complex, the use of the combination mode poses certain challenges.
Participants:
Component: Specifies the object declaration interface in the combination. When appropriate, it implements the default behavior of interfaces common to all classes. Declare an interface to access and manage Component sub-parts.
Leaf: Leaf object. The leaf node does not have any subnode.
Composite: A container object that defines the behavior of a node. It is used to store sub-parts. operations related to sub-parts are implemented in the Component interface, such as add and remove.
4. Decorator)
We can add behavior to an object by means of inheritance and combination. Although inheritance can have a good parent class behavior, it has several defects: 1. If the relationship between objects is complex, the system becomes complicated and is not conducive to maintenance. 2. It is prone to "Explosion-like. 3. Static. Here we can solve this problem by using the modifier mode.
The modifier mode dynamically attaches the responsibility to the object. To expand the functionality, the decorator provides an alternative solution that is more flexible than inheritance. Although the modifier mode can dynamically attach responsibility to objects, it produces many small objects, increasing the complexity of the system.
Participants:
Component: Abstract Component. Is to define an object interface, you can dynamically add responsibilities to these objects.
ConcreteComponent: component. Is to define a specific object, you can also add some responsibilities to this object.
Decorator: Abstract decoration class. It is a decorative abstract class that inherits Component and extends the functionality of the Component class from the external class. However, for Component, you do not need to know the existence of the Decorator.
ConcreteDecorator: Specifies the decoration class to add responsibilities to Component.
5. Facade)
We all know that the lower the coupling between classes, the better the reusability. If the two classes do not need to communicate with each other, do not let the two classes have a direct relationship, if you need to call the method, you can forward the call through a third party. The appearance mode is a good explanation of this section. The appearance mode provides a unified interface to access a group of interfaces in the subsystem. It minimizes the interdependence between application neutron systems. It provides a simple and single barrier for the sub-system to communicate with the sub-system through this barrier.
By using the appearance mode, the customer's reference to the subsystem becomes simple, and the loose coupling between the customer and the subsystem is realized. But it violates the "open and closed principle", because adding a new subsystem may need to modify the source code of the appearance class or client.
Participants:
Facade: appearance role. You need to know which sub-system classes are responsible for processing requests and delegate customer requests to suitable sub-systems for processing.
SubSystem: SubSystem role. Implement sub-system functions to process requests sent from Facade objects.
6. Flyweight)
Objects in a system occupy too much memory, especially those with a large number of repeated objects, which is a great waste of system resources. The sharing mode provides a solution for reusing objects. It uses the sharing technology to reuse identical or similar objects.
The metadata sharing mode is used to run the sharing technology to effectively support the reuse of a large number of fine-grained objects. The system uses a small number of objects, which are similar and with small state changes, which can be reused multiple times. Note: The metadata mode requires that objects that can be shared must be fine-grained objects.
The share mode greatly reduces the number of objects in the system through the sharing technology. At the same time, the share mode uses the internal status and external status, and the external status is relatively independent, without affecting the internal status, therefore, the metadata sharing mode allows the metadata objects to be shared in different environments. At the same time, it is divided into internal and external States. The meta-mode will make the system more complex, and it will also lead to a long time to read the external state.
Participants:
Flyweight: Abstract metadata class. Flyweight can accept and act on external topics through the superclasses or interfaces of specific Metadata classes.
ConcreteFlyweight: the metadata class. Specify the internal status to add storage space for the internal status.
UnsharedConcreteFlyweight: A non-shared metadata class. Specify the Flyweight subclasses that do not need to be shared.
FlyweightFactory: the metadata factory class. Used to create and manage Flyweight objects. It is mainly used to ensure reasonable sharing of Flyweight. When a user requests a Flyweight, flyweightFactory provides a created Flyweight object or creates a new one (if it does not exist ).
7. Proxy ),
The proxy mode provides a proxy for an object and controls the reference to the original object by the proxy object. It prevents the customer from directly communicating with the real target object. The proxy object is the representative of the target object. Other operations that need to deal with this target object are negotiated with this proxy object.
Proxy objects can play an intermediary role between the client and the target object, which plays a role and protects the target object, and also reduces the Coupling Degree of the system to a certain extent.
Participants:
Subject: Abstract role. Declares the common interfaces of real objects and proxy objects.
Proxy: Proxy role. The proxy object implements the same interface as the real object, so it can proxy the real object at any time. The proxy role contains a reference to a real object, so she can operate on the real object and append other operations, which is equivalent to encapsulating the real object.
RealSubject: real role. It represents a real object and is the object we will reference in the end.
Iv. Behavior Model
Behavioral patterns are mainly used to describe how classes or objects interact and how responsibilities are assigned. It involves the assignment of duties between algorithms and objects. It not only describes the object or class mode, but also describes the communication mode between them, it transfers your attention from the control flow to the relationship between objects. The behavior-type class mode uses the Inheritance Mechanism to distribute behavior among classes, while the behavior-type object mode uses Object combination instead of inheritance. It mainly includes how to design patterns in 11: responsibility chain mode, command mode, interpreter mode, iterator mode, intermediary mode, memo mode, observer mode, status mode, policy mode, template method mode, and visitor mode.
1. Chain of Responsibility)
The responsibility chain mode describes how requests are transmitted along the chain composed of objects. It makes up an object into a chain. The sender sends the request to the first receiver of the chain and transmits the request along the chain, it remains at the end of the chain until an object is processed or no object is processed at the end.
To avoid coupling between request senders and receivers, multiple objects may receive requests, connect these objects into a chain, and pass requests along the chain, this is the responsibility chain mode until an object processes it. In the responsibility chain mode, every object can process the request, thus realizing the decoupling between the request sender and the receiver. At the same time, the responsibility chain mode simplifies the object structure, so that each object only needs to reference its successor, without having to understand the entire chain, this not only improves the system flexibility, but also makes it easier to add new request processing classes. However, in the responsibility chain, we cannot ensure that all requests can be processed, and it is not conducive to observing runtime features.
Participants:
Handler: the abstract processor. Defines a request processing method. All processors must implement this abstract class.
ConcreteHandler: the handler. Processes the requests it is responsible for and can also access its successor. If it can process the request, it will process it; otherwise, it will pass the request to its successor.
Client: Customer class.
2. Command)
Sometimes we want to send a request to an object, but we do not know who the specific receiver of the request is and how the specific processing process is, you only need to specify the specific request receiver in the program running. For the command mode that encapsulates the request into an object, we call it. Therefore, in command mode, requests are encapsulated into objects so that different requests, queues, or logs can be used to parameterize other objects. The command mode also supports unrecoverable operations.
The command mode can completely decouple the request sender and receiver. There is no direct connection between the sender and receiver. The sender only needs to know how to send the request command, and the rest can be ignored, you don't even need to worry about whether the command is successful or not. At the same time, we can easily add new commands, but it may be because the convenience and encapsulation of requests will cause too many specific command classes in the system.
Participants:
Command: Abstract Command class. The interface used to declare the operation.
ConcreteCommand: Specifies a command class. Binds a recipient object to an action, and calls the corresponding operation of the receiver to implement Excute.
Invoker: caller. This command is required to execute this request.
Receiver: the Receiver. Knowing how to perform operations related to executing a request, any class may become a receiver.
Client: Customer class.
3. Interpreter Mode)
The interpreter mode defines the grammar of a language and creates an interpreter to explain sentences in the language. The interpreter mode describes how to construct a simple language interpreter. It is mainly used in compilers developed using object-oriented languages. It describes how to define a grammar for a simple language, how to represent a sentence in the language, and how to explain these sentences.
Participants:
AbstractExpression: an abstract expression. Declares an abstract interpretation operation, which is shared by all nodes in the abstract syntax tree.
TerminalExpression: The Terminator expression. Implements explanations related to Terminators in grammar. Implement the methods required in the abstract expression. Each terminator in a grammar has a specific Terminator expression corresponding to it.
NonterminalExpression: A non-terminator expression. Explain operations related to non-terminator in grammar.
Context: Environment class. Contains global information other than the interpreter.
Client: Customer class.
4. Iterator)
Iteration is often used in programming. It can walk every element in aggregation and provide different traversal methods. This is the design motivation of the iterator mode. In our actual development process, we may need to traverse the entire object in different ways according to different requirements, however, we do not want to fill in different traversal operations in the abstract interfaces of aggregate objects, so we want something to traverse an aggregate object in a variety of different ways, the iterator mode appears.
What is the iterator mode? The so-called iterator mode provides a method to access each element in an aggregate object sequentially, rather than exposing its internal representation. In the iterator mode, the responsibility of the iteration element is handed over to the iterator instead of the aggregate object. We can implement the iteration of the aggregate object without knowing the internal structure of the aggregate object.
Through the iterator mode, the structure of the aggregate object is simpler. Instead of focusing on the traversal of its elements, it only needs to focus on what it should be focused on, so that it is more in line with the single responsibility principle.
Participants:
Iterator: Abstract Iterator: the interface that all iterators need to implement. It provides a method to walk through and aggregate object elements.
ConcreteIterator: Specific iterator. This iterator can be used to traverse specific aggregate objects. Each aggregate object should correspond to a specific iterator.
Aggregate: abstract Aggregate class.
ConcreteAggregate: Aggregate class. Implement the creatorIterator () method and return the iterator of the aggregate object.
5. Mediator)
Rent a house, everyone has had experience! In this process, the intermediary structure plays a very important role. It serves as an intermediary and transmits information to us and the homeowner. Such an intermediary is also needed in the world of external software. In our system, there are sometimes strong and complex associations between objects. If they are directly connected, it will inevitably make the entire system very complex and has poor scalability! We know that if there is no need to communicate with each other between the two classes, we should not directly associate them. If we really need to communicate with each other, we can forward their requests through third parties. Similarly, we use the intermediary to solve this problem.
The so-called intermediary mode is to use an intermediary object to encapsulate a series of object interactions. The intermediary makes the objects do not need to be explicitly referenced to each other, so that their coupling is loose, in addition, the interaction between them can be changed independently. In the intermediary mode, an intermediary object is used to encapsulate the relationship between objects. Each object can communicate with each other without knowing the specific information. It reduces the relationship between objects, provides system reusability, and simplifies the system structure.
In the intermediary mode, each object does not need to know each other. They only need to know the intermediary object, however, the intermediary object must know the relationship between all objects and them. This is precisely because the structure of the intermediary object is too complex and has assumed too many responsibilities, at the same time, it is also the core of the entire system. If there is a problem with it, it will lead to the problem of the entire system. Therefore, if there is a "many to many" complex relationship group in the system design process, do not rush to use the intermediary mode, instead, consider whether the system you designed has problems.
Participants:
Mediator: Abstract intermediary. Defines the interface between the colleague object and the intermediary object.
ConcreteMediator: the intermediary. To implement an abstract intermediary method, you need to know all the specific colleagues' classes, receive information from the specific colleagues' classes, and send information to the specific colleagues' classes.
Colleague: Abstract Colleague class.
ConcreteColleague: a specific colleague class. Each specific colleague class only needs to know their own behavior, but they all need to know the intermediary.
6. Memento)
People all want regret medicine, but the fact is cruel, there is no regret medicine to buy, but not only that, there is regret medicine in the world of software! The memorandum model is a kind of regret. It provides a mechanism for our software to restore the system to a specific historical state.
The so-called memorandum mode captures the internal state of an object without damaging the encapsulation, and saves the State outside the object, in this way, the object can be restored to the previously saved State later. It encapsulates information so that the customer does not need to care about the details of state storage. Saving consumes resources, so the disadvantage of the memorandum mode is that it consumes resources. If the class has too many member variables, it will occupy a large amount of resources and consume a certain amount of memory each time it is saved.
Participants:
Originator: The primary machine. Creates a memorandum to record the internal status of the current object. It can also be used to restore the internal status. At the same time, the primary node can also determine the internal states of Memento storage Originator as needed.
Memento: Memorandum. Stores the internal status of Originator and prevents objects other than Originator from accessing Memento. There are two interfaces in the memorandum Memento. The Caretaker can only see the narrow interface in the memorandum, and it can only pass the memorandum to other objects. Originator can see the wide interface, allowing it to access all data returned to the previous state.
Caretaker: owner. It is responsible for keeping the memorandum. It is not allowed to operate and access the content of the memorandum, but to pass the memorandum to other objects.
7. Observer mode (Observer)
What is the observer mode? The observer mode defines the one-to-many dependency between objects. In this way, when an object changes its status, all its dependent persons will receive notifications and update them automatically.
Here, the object to be changed is called the observation object, and the object to be notified is called the observer. One observation target can correspond to multiple observers, and there is no mutual relationship between these observers. Therefore, you can add and delete observers as needed, making the system easier to expand.
Therefore, the observer provides an object design that allows the subject to be loosely coupled with the observer.
Participants:
Subject: target. He saves all references to the observer's play in one aggregation. Each topic can have multiple observers.
Observer: Observer. Define an interface for all the specific observers to promptly update themselves when receiving notifications of the topic.
ConcreteSubject: a topic. Store the relevant status to a specific observer object. Send notifications to all observers when the subject changes.
ConcreteObserver: Specific observer. Implements the update interface required by the abstract observer role to coordinate its status with the topic status.
8. State)
In many cases, the behavior of an object depends on one or more of its changing attributes. These variable attributes are called states, that is, behavior dependent States, that is, when the status of the object changes due to external interaction, its behavior will also change accordingly. In this case, we cannot use behavior to control changes in the state. Instead, we should consider behavior from the State perspective, that is, what status should be done. This is the status mode.
Therefore, the State mode allows an object to change its behavior when its internal state changes. The object seems to have modified its class.
In the state mode, we can reduce the large if... Else statement, which combines the state conversion logic with the State object, but reduces if... The cost of the else statement is to get a large number of classes, so the state mode is bound to increase the number of classes or objects in the system.
At the same time, the state mode puts all actions related to a certain state into a class, and can easily add new States. You only need to change the object State to change the behavior of the object. However, this will make the system structure and implementation more complex. Improper use will lead to program structure and code confusion, which is not conducive to maintenance.
Participants:
Context: Environment class. It can include some internal states.
State: abstract State class. State defines a common interface for all specific States. All States implement the same interface, so that States can be converted to each other.
ConcreteState: Specifies the status class. The specific status class is used to process requests from the Context. Each ConcreteState provides its implementation of its own requests. Therefore, when the Context changes its status, its behavior also changes.
9. Strategy)
We know that there may be many ways to implement one thing, but there is always one of the most efficient ways, the same in the world of software development, we also have many methods to implement a function, but we need a simple and efficient way to implement it so that the system can be very flexible. This is the policy mode.
Therefore, the policy mode defines the algorithm family and encapsulates them separately so that they can convert each other. However, this mode is independent of the customers who use the algorithm.
In the policy mode, it defines these methods to solve the problem as an algorithm group. Each method corresponds to a specific algorithm. Here, an algorithm is called a policy. Although the rule mode defines algorithms, it does not provide algorithm selection, that is, what algorithms are most suitable for what problems this is not concerned about the policy mode, so the choice of policies should be done by the client. The customer must clearly know the differences between each algorithm and when and where to use the most appropriate policy, which increases the burden on the client.
At the same time, the policy mode perfectly complies with the "open and closed principle". You can choose algorithms or actions without modifying the original system, or flexibly add new algorithms or actions. However, a policy corresponds to a class which will generate many policy classes by the system.
Participants:
Context: Environment class. Maintain the reference of a Strategy object and configure it with a ConcreteStrategy. You can define an interface to allow Strategy to access its data.
Strategy: Abstract Strategy class. Define all public interfaces that support algorithms. Context uses this interface to call a Concretestrategy-defined algorithm.
ConcreteStrategy: specific policy class. Encapsulates specific algorithm implementations.
10. Template Method)
In some cases, the steps for doing a few things are almost the same. They are only a small difference. In the world of software development, if we do all these steps one by one, time-consuming, laborious, and thankless. Therefore, we can break down and encapsulate these steps, and then use the Inheritance Method to inherit them. Of course, you can rewrite the implementation by yourself! This is the solution provided by the template method mode.
The so-called template method mode defines the skeleton of an algorithm in a method, and delays some steps to the subclass. The template method allows subclass to redefine some steps in the algorithm without changing the algorithm structure.
The template method mode is based on the inherited code reuse technology. In the template method mode, we can place the same part of code in the parent class, And put different codes into different subclasses. That is to say, we need to declare an abstract parent class, implement part of the logic in the form of a specific method and a specific constructor, and then declare some abstract methods so that sub-classes can implement the remaining logic, different sub-classes can implement these logics in different ways. Therefore, the template of the template method is actually a common method, but this method encapsulates the steps of algorithm implementation.
Participants:
AbstractClass: abstract class. A template is implemented to implement the basic skeleton of the algorithm. The specific subclass will redefine the primitiveOperation () method to implement an algorithm step.
ConcreteClass: a subclass. Implement the primitiveOperation () method to complete the steps related to the specific subclass in the algorithm.
11. Visitor mode (Visitor)
The visitor mode is commonly known as the most difficult of the 23 major design patterns. In addition to complex structures, it is also difficult to understand. In our software development, we may have different processing methods for the same object. If we handle them separately, catastrophic errors will occur. The visitor mode provides a better solution to this problem.
The visitor mode is an operation that acts on each element in an object structure. It allows us to define new operations that act on these elements without changing the classes of each element.
The purpose of the visitor mode is to encapsulate operations applied to a certain data structure element. Once these operations need to be modified, the data structure that accepts the operation can remain unchanged. Multiple Access methods are provided for different types of elements, and new operation methods can be added without modifying the original system. At the same time, we need to make it clear that the visitor mode is suitable for those data structures that are relatively stable, because it separates data operations from data structures, if the data structure of a system is relatively stable, but the operation algorithm is easy to change, the visitor mode is more suitable, because the visitor mode makes the increase of algorithm operations easier.
Reading Notes ----- simple factory Model
02. Design Mode Reading Notes-factory method mode
03. Design Model Reading Notes ----- Abstract Factory Model
04. Design Mode Reading Notes ----- builder Mode
05. Design Mode Reading Notes-prototype mode 11
06. Design Mode Reading Notes-singleton Mode
07. Design Mode: Reading Notes ----- adapter Mode
08. Design Mode Reading Notes ----- Bridge Mode 11
09. Design Mode Reading Notes ----- Combination Mode
10. Design Mode: Reading Notes ----- decorating Mode
11. Design Mode Reading Notes ----- appearance Mode
12. Design Mode: Reading Notes ----- Yuan-Sharing Mode
13. Design Mode Reading Notes ----- proxy Mode
14. Design Mode Reading Notes-responsibility chain mode
15. Design Mode Reading Notes-command mode
16. Design Mode Reading Notes ----- interpreter Mode
17. Design Mode Reading Notes ----- iterator Mode
18. Design Mode Reading Notes-intermediary Mode
19. Design Mode Reading Notes-Memorandum Mode
20. Design Mode Reading Notes ----- observer Mode
21. Design Mode Reading Notes ----- status Mode
22. Design Mode Reading Notes-Strategy Mode
23. Design Mode Reading Notes ----- template Mode
24. Design Mode Reading Notes ----- visitor Mode
6. Conclusion
Thanks to the Head First design patterns written by Eric Freeman, elisw.freeman, and Kathy sield & Bert Bates, this book leads me to the design pattern, even though it has just crossed the threshold, however, I have been immersed in the thick and mellow knowledge. I would also like to thank Mr. Liu Wei for his PPT. Your tutorial gave me a good reference.
Although I have read the design model, it is not the end, but the beginning. In the future project process, I will try my best to optimize and think about it.
It is true that the Foundation is not solid enough in the project process recently, so the next step is the java Foundation: think in java, I must conquer you !!!!
This blog is a bit long. Thank you for reading it. If you think it is good, please recommend it !!!!