Back

Let's talk about design patterns

Wed, Jul 08 20202 min read
Nathaniel

What is a design pattern

Design pattern is a method of solving specific problems through definition, use, and testing. It is a universal and reusable solution proposed for the repetitive problems in software design under given conditions. Design patterns cannot Directly translated into a complete design of the code, it is used to describe a general solution for solving problems in different situations.

The role of design patterns

Design patterns accelerate the development process by providing proven and effective development paradigms, prevent major hidden problems, and improve code readability.

Classification of design patterns

  1. Creative design model
  2. Structural design mode
  3. Behavioral design patterns

Creative design pattern

Pay attention to complete the instantiation of objects. Compared with directly instantiating objects, choosing appropriate design patterns to complete the instantiation of objects according to the actual situation can bring higher flexibility to complex business scenarios. Creative design patterns mainly include the following:
  1. Abstract factory design pattern
  2. Generator design pattern
  3. Factory method design pattern
  4. Prototype design mode
  5. Singleton design pattern

Structural design pattern

The structural design pattern is used to guide us to complete the structural division of the code. In this way, the code structure will be clearer and easier to understand, and it also improves the maintainability of the software. Structural design patterns mainly include the following:
  1. Adapter design pattern
  2. Bridge design pattern
  3. Combination design pattern
  4. Decorative design patterns
  5. Facade design pattern
  6. Flyweight design mode
  7. Agency design pattern

Behavioral Design Pattern

Behavioral design patterns are mainly used to define the communication and process control between objects. The main design patterns are all focused on optimizing the way of data interaction between objects. Behavioral design patterns mainly include the following:
  1. Chain of Responsibility Design Pattern
  2. Command design pattern
  3. Interpreter design pattern
  4. Iterator design pattern
  5. Intermediary design pattern
  6. Memo design pattern
  7. Observer design pattern
  8. Strategy design pattern
  9. State design pattern
  10. Template method design pattern
  11. Visitor Design Pattern

How to learn design patterns

-What is the name of the mode? -What is the mode type? Is it creative, structural, or behavioral? -What is the purpose of the model? (What's the role? What problem does it solve?) -What is the alias of the pattern? -When to use this mode? -Basic example of the pattern -What is the UML diagram of this model? Is it a class diagram or an interactive diagram? -Which objects are involved in activities in the mode? List the classes and objects used in the design pattern, and explain their respective roles -How do the classes and objects in the pattern interact? -What are the benefits and disadvantages of applying design patterns? How to weigh? -How to implement this mode -What is the design pattern similar to this pattern? What are the similarities and differences between these similar models?

Look at design patterns in a correct way

Appropriate use of design patterns can improve code reusability, but because reusability often introduces encapsulation and indirect calls, these will reduce system performance and increase code complexity. Therefore, unless design patterns can help us complete code implementation or subsequent maintenance work, there is no need to introduce design patterns. The key to learning design patterns is not to learn the design patterns themselves, but to identify application scenarios and potential risks, and to use the design patterns in a proper way. In this way, design patterns can be regarded as handy tools. It is not necessary to use design patterns when it is not necessary, because design patterns may sacrifice the simplicity of the code, and abuse of design patterns often introduces new problems but does not solve the original problems. Keep the code tidy, modular and readable, and don't allow excessive coupling between various types.

Creative design model

The creative design pattern mainly focuses on the instantiation of classes, which means that it reflects the creation method of objects. Using these patterns, we can create objects in appropriate forms under appropriate circumstances. The creative design patterns control the object's Created to solve problems in the design. Creative design patterns mainly include the following subcategories:
  1. Object creation design mode:
Mainly complete the object creation, and put part of the content of the object into other objects to create.
  1. Class-creative design mode:
Mainly complete the instantiation of the class, and put part of the objects in the class into subclasses to create, this type of mode efficiently uses the inheritance mechanism in the instantiation process The creative design pattern mainly includes the following 5 specific design patterns:
  1. Abstract factory design pattern
Provide an interface for creating related objects or interdependent objects without specifying the specific class of the object
  1. Generator design pattern
Separate the construction of complex objects from their representations so that the same construction process can create different representations
  1. Factory method design pattern
Allows to implement instantiated classes of this class in subclasses
  1. Prototype design mode
Use a prototype instance to specify the type of object to be created, and then copy these prototypes to achieve the creation of new objects
  1. Singleton mode
Ensure that a certain class has only one instance in the system, and provide a global access point to access it
Object-creative design patternClass-creative design pattern
Abstract Factory Design PatternFactory Method Design Pattern
Generator design pattern
Prototype design mode
Singleton Design Pattern

Factory Method Design Pattern

The role of the factory method is to create objects, used to instantiate an object from a set of classes that implement specific logic.

Classes included in the pattern

-The product class (Product) defines the object interface created by the factory method. -The concrete product class (Concrete Product) implements the product class interface. -The factory class (Creator, because it creates the product class, so called the factory class) declares the factory method and returns a product class object. Can be used to call the generation method of creating a product object. -The concrete factory class (Concrete Creator) rewrites the method used to create the concrete product class object.

UML diagram

Functions and application scenarios

-When a class needs to be created, and the type of this class cannot be determined during programming (determined at runtime). -When a class wants its subclasses to specify the specific type of the created object. -When we want to locate the created class and obtain related information.

Abstract factory design pattern

The abstract factory pattern has a higher level of abstraction than the factory method pattern. This means that the abstract factory returns a set of factories. Similar to the factory method pattern (returning one of multiple subclasses), this method will return a factory, and this factory will return one of multiple subclasses. Simply put, an abstract factory is a factory object, which in turn returns one of several factories. The factory model is a typical example of the creative model. The abstract factory design pattern is an extension of the factory method pattern, so that we can create objects without worrying about the actual class of the created object. The abstract factory pattern extends the factory method pattern, allowing the creation of more types of objects.

Classes included in the pattern

-Abstract Factory (AbstractFactory) declares an interface used to complete the creation of abstract product objects. -Concrete Factory (ConcreteFactory) realizes the operation of creating concrete product objects. -AbstractProduct (AbstractProduct) declares an interface for a class of product objects. -Concrete Product (ConcreteProduct) defines the product object created by the corresponding concrete factory. -The client uses the only interface declared by the abstract factory and abstract product class.

UML diagram

Functions and application scenarios

One of the main advantages of the abstract factory pattern is that it shields the creation methods of these concrete classes. The actual application class name does not need to be known to the client (decouple the client from the specific class). Since the specific class is shielded, we can switch between different factories (implementation methods).

Generator design pattern

The generator mode can generate complex objects step by step from simple objects. The generator mode is a creative mode used to build complex objects step by step and return to the object in the last step. The process of constructing an object is implemented through generics so that it can be used to create different representations of the same object.

Classes included in the pattern

-Builder class (Builder) provides an interface for creating various components of the product. Concrete Builder (Concrete Builder) provides the realization of this connection. -The concrete builder (ConcreteBuilder) will track the manifestation of the objects it creates, and provide an interface to obtain the product while creating the object. -Director constructs objects through the interface provided by the generator. Product classes are used to represent complex objects being constructed. This includes defining all the classes we build.

UML diagram

Functions and application scenarios

The generator mode hides the internal details of the product building process. Each generator is independent of each other. This improves the modularity of the code and makes it easier for other generators to create objects. Because each generator can create objects step by step, this allows us to have a good control over the final product.

Singleton Design Pattern

In the entire life cycle of the application, when the object has only one instance, the singleton design pattern will be used. The singleton class is always instantiated the first time it is accessed, and only the same instance will be used until the application exits. Singleton creation strategy: We restrict the instantiation of singleton classes by restricting the constructor (by setting it as private). Later, when defining the class, include a static private object of the class to create an instance of the singleton class. In the singleton mode, the trickiest part is the realization and management of the single instance. In the process of defining the singleton pattern, there are two points to note:
-Only one instance of this class is allowed. -Need to provide a global access point for the single instance.
Active instantiation and passive instantiation in singleton mode (hungry man, lazy man) Thread-safe singleton: double synchronization locks, static variables, enumerations

Classes included in the pattern

-Singleton

UML diagram

Functions and application scenarios

In the entire life cycle of the application, when the object has only one instance, the singleton design pattern will be used.

Prototype design mode

Compared with the previous time-consuming and laborious creation of a complex object, the prototype mode only needs to copy existing similar objects and make appropriate modifications as needed. Prototype means using the clone method. The clone method is an operation to copy an object. The cloned copy of the object is initialized to the current state of the original object when the clone method is called. This means that the cloning of objects avoids the creation of new objects. If the cost of creating a new object is high, and it may cause resource strain, we clone the object.
-Shallow copy: When the original object changes, the new object also changes. This is mainly because shallow copy does not actually copy the new object, but only a reference to the original object. -Deep copy: When the original object changes, the new object is not affected, because all the parameters, objects, and references contained in the original object have created a new copy during the process of copying the new object.
When using the clone method to copy objects, whether to use shallow copy or deep copy is determined by business requirements. When using prototype mode
However, using the clone method to copy objects is only a design decision. The cloning method is not a mandatory best choice for the prototype mode.

Classes included in the pattern

-Client: Create a new object by calling the clone operation of the prototype class. -Prototype: declare an interface to clone yourself. -Concrete Prototype: Realize the operation of cloning yourself.

UML diagram

Functions and application scenarios

  1. When a system should be independent of the creation, combination and presentation of its products.
  2. When the class that needs to be instantiated is defined at runtime, such as dynamic loading, or to avoid establishing a factory class inheritance hierarchy parallel to the product class inheritance hierarchy.
  3. When an instance of a class can only have one of several different combinations of states. Using the prototype mode to establish a corresponding number of prototypes and clone methods will be more convenient than manually instantiating the class and configuring the corresponding state each time.
Main difficulty:
-Each subclass of the prototype class must implement the cloning operation. This can be difficult to achieve. For example, it may be difficult to add a clone method when the class already exists. -When the object contains other objects that do not support cloning or objects with circular references, it will be more difficult to implement the cloning method.
advantage:
-Prototype mode means to use the clone method. The clone method is an operation to copy an object. Compared with the time-consuming process of creating duplicate objects, the prototype mode only duplicates similar existing objects, and then modifies the duplicated copies as needed. -The client can add or remove prototype objects at runtime. -Define new objects through various parameters: A highly dynamic system allows us to define new characteristics by using object combinations, such as assigning corresponding parameter values ​​to object variables instead of redefining a class. We can effectively define new types of objects by instantiating existing classes and register prototype instances for client objects. The client can assign a certain responsibility to the prototype class to give it new characteristics. This design allows users to easily define new classes without extensive programming. In fact, cloning a prototype is essentially similar to the instantiation of a class. But the prototype mode can greatly reduce the number of classes required by the system.
side effect:
-Using the prototype mode, we can add and delete objects at runtime through object cloning as needed. We can modify the internal data representation of the class at runtime according to the running status of the program. -A major difficulty in implementing the prototype pattern in Java is that if these classes already exist, we may not be able to modify the class by adding the required clone method or deep clone method. In addition, those classes that have a circular reference relationship with other classes cannot really implement cloning. -You need to have sufficient data access rights or methods in these classes to modify the corresponding data after the cloning is completed. This may require adding corresponding data access methods to these prototype classes so that we can modify the data after the class is cloned.

Structural design pattern

The structural pattern mainly describes how to combine objects and classes to form more complex structures. In software engineering, the structural pattern is a design pattern used to help designers identify and realize the relationship between objects in a simple way. The structured model organizes programs in groups. This form of division makes the code clearer and easier to maintain. Structural mode is used for the structural organization of code and objects. The structured model organizes programs in groups. This form of division makes the code clearer and easier to maintain. Structural models are further divided into the following subcategories:
  1. Object structure mode: used to associate and organize objects to form a larger and more complex structure.
  2. Class structure mode: used to implement code abstraction based on inheritance, and will introduce how to provide a more useful program interface through this mode.
Specifically include:
Object structure modelClass structure model
Bridge ModeClass Adapter Mode
Combination Mode
Decoration mode
Facade Mode
Flyweight Model
Object Adapter Mode
Agency Model
  1. Combination mode: It can handle various complex and flexible tree structures for the client. These tree structures can be composed of various types of containers and leaf nodes, the depth or combination of which can be adjusted or determined at runtime.
  2. Decoration mode: Allows us to dynamically modify objects at runtime by adding new functions or modifying existing functions.
  3. Facade mode: allows us to create a unified interface for the client to access different interfaces of different subsystems, thereby simplifying the client.
  4. Flyweight mode: A large number of objects will be created at runtime when the client calls a class. This mode will redesign the class to optimize memory overhead.
  5. Proxy mode: Provide a proxy for other objects to control access to this object. The purpose of this mode is that an object is not suitable or cannot directly reference another object, simplifying the client and implementing object access, while avoiding any side effects.
  6. Adapter mode: Allows us to provide a new interface for an existing class, and realize the reuse of the class when the client requests a different interface.
  7. Bridge mode: allows us to decouple the class and its interface from each other. Allow classes and their interfaces to change independently of each other over time, increase the number of times that classes are reused, and improve subsequent scalability. It also allows dynamic switching of different implementations of the interface at runtime, making the code more flexible.

Adapter design pattern

The working principle of the software adapter is exactly the same as that of the socket adapter. We also often need to use different classes or modules in our programs. Suppose there is a piece of code that is poorly written. If we directly integrate this code into the program, the existing code will be messed up. But we have to call this code, because we need to implement related functions, and writing from scratch will waste a lot of precious time. The best practice at this time is to write the adapter and package the required code. In this way, we can use a custom interface, thereby reducing the dependence on external code. The adapter mode will convert the existing interface into a new interface, and the goal of compatibility and reusability of irrelevant classes in the application has been achieved. The adapter mode is also called the packaging mode. The adapter pattern can help classes that cannot work together due to incompatible interfaces so that they can work together. The adapter mode is also responsible for converting the data into an appropriate form. When the client specifies its requirements for the data format in the interface, we can usually create a new class to implement the interface and subclasses of the existing class. This way of implementation will also implement the conversion of the interface between the client calling command and the called method in the existing class by creating a class adapter.

Classes included in the pattern

-The client (Client) calls the class or program of the target class. -Target class (Target) the interface that the client wants to use. -Adaptation object class (Adapetee) The class or object that needs to be adapted. -Adapter class (Adapter) according to the requirements of the target class interface to implement the adaptation conversion of the interface form of the adaptation object interface. -request method: the operation the client wants to perform. -specificRequest method: the realization of the request method function can be completed in the adaptation object.

UML diagram

Functions and application scenarios

In specific practice, there are two ways to actually apply the adapter pattern:
  1. Use inheritance [Class Adapter]
  2. Use Association [Object Adapter]
Application scenario:
-We want to use an existing class, but its interface does not meet our needs. -We want to create a reusable class that can collaborate with some unrelated classes or unforeseen classes, and this class does not need to have compatible interfaces. -(Only applicable to object adapters) We need to use multiple existing subclasses, and it is obviously impractical for us to do interface adaptation for each subclass. Use the object adapter to directly adapt to the interface of its parent class.

Bridge design pattern

The bridge mode is another typical mode in the structural mode. The bridge mode is used to decouple the interface of the class from the implementation of the interface. This improves the flexibility of the system so that both the interface and the implementation can be changed independently. As an example, let us think of household appliances and their switches. For example, the switch of a fan. The switch is the control interface of the electrical appliance, and once the switch is closed, it is the fan motor that actually makes the fan run. Therefore, in this example, the switch and the fan are independent of each other. If we connect the switch to the power supply line of the light bulb, then we can also use other switches to control the fan.

Classes included in the pattern

-Abstraction bridges the core of the design pattern and defines the key crux. Contains references to realized objects. -Extend RefinedAbstraction (RefinedAbstraction) to extend the abstract object and refine the abstract object to a new level. Hide detailed elements from the realized object. -Implementor The interface has a higher level than abstract objects. Only the basic operations are defined. -The concrete realization object (Concretelmplementor) performs the concrete functions of the realization object by providing concrete realization.

UML diagram

Functions and application scenarios

The bridging mode is mainly suitable for situations where multiple dimensions of the system often change. The bridge mode can connect different abstract dimensions. Through the bridge mode, abstract objects and realized objects will not be bound at compile time, but can be independently extended when their respective classes are called. The bridge mode is also very useful when you often need to switch between multiple implementations at runtime.

Combination design pattern

In most system development processes, programmers will encounter situations where a component can be either an independent individual object or a collection of objects. Combination mode is used in the design of such situations. To put it simply, a combination mode is a collection of a group of objects, and each object in this group of objects is also an object composed of a combination mode, or just a primitive object. There is a tree structure in the combined mode, and the same operations can be performed on the branch nodes and leaf nodes in the structure. Each branch node in the tree structure contains a class of child nodes (which can inherit leaf nodes and branch nodes). Such a branch node itself is a node composed of a combined pattern. The leaf node in the tree structure is only an original object, and it has no child nodes (leaf nodes and branch nodes cannot be inherited). The subcategories of the combined mode (the next level node) can be leaf nodes or other combined modes.

Classes included in the pattern

-Component object: (Component, structure) -The component object is at the top of the entire inheritance structure. It is an abstraction of the combination mode. -It declares the object interface in the composite mode. -You can optionally define an interface to access the parent class of the component in the recursive structure and implement the interface when needed. -Leaf node: (Leaf, original object) -At the end of the tree structure, there will be no more child nodes. -Defines the behavior of individual objects in the composite structure. -Branch node class: (Composite, group) -Include subcomponents and define behaviors for them. -Implement related operations of child nodes.

UML diagram

Functions and application scenarios

-When a collection of objects needs to be handled in the same way as a single object. -When manipulating a single object is similar to manipulating a group of objects. -Note that there are recursive structures or tree structures that can be combined. -Customers
The end can access the entire inheritance structure through the component object, but they do not know whether they are dealing with leaf nodes or branch nodes.
The purpose of the combined mode is to enable independent objects (single branch nodes or leaf nodes) and object collections (subtrees) to be organized in the same way. All objects in the combined mode come from themselves (become a nested structure). The combination mode allows us to recursively combine similar objects into a tree structure to realize the construction of complex structural objects.

Decorator design pattern

Decorative design patterns are used to extend or modify the functionality of an instance at runtime. Generally speaking, inheritance can extend the functionality of a class (for all instances of the class). But unlike inheritance, through the decoration mode, we can select an object of a class and modify it without affecting other instances of this class. Inheritance will directly add functionality to the class, while the decoration mode will add functionality to the class by packaging the object with other objects.

Classes included in the pattern

-Abstract Component (Component) gives an abstract interface for objects that can dynamically add functionality. -Concrete Component defines an object that implements the component interface. This is the object that actually needs to be decorated, but it does not know anything about the process of decoration.

UML diagram

Functions and application scenarios

Decorative design patterns are used to extend or modify the functionality of an instance at runtime. Generally speaking, inheritance can extend the functionality of a class (for all instances of the class). But unlike inheritance, through the decoration mode, we can select an object of a class and modify it without affecting other instances of this class. Inheritance will directly add functionality to the class, while the decoration mode will add functionality to the class by packaging the object with other objects.

Facade design pattern

Many business processes involve complex business operations. Due to the complexity of the process, it involves multiple business objects, which often leads to tight coupling between various classes, thereby reducing the flexibility of the system and the clarity of the design. The complex relationship between the underlying business components makes it difficult to write client code. Facade mode simplifies the external interface to complex systems. For this it will integrate all the classes and build a subsystem of a complex system. The facade mode can shield users from the complex details inside the system, and only provide users with simplified external interfaces that are easier to use. At the same time, it also decouples the internal code of the system and the code of the interface subsystem to modify and upgrade the system code. Compared with other design patterns, the facade pattern pays more attention to the decoupling of the code. It emphasizes a very important point in code design, namely code abstraction. By providing a simple interface and hiding the complexity behind, so as to achieve abstraction. In this way, the realization of the code is completely handled by the facade layer. The client can only interact with one interface, and only has the permission to interact with this interface. In this way, the complexity of the entire system can be hidden. All in all, the facade mode simplifies the interaction with complex systems for clients by providing a simple interface. On the other hand, the facade mode also ensures that the specific implementation method can be modified without modifying the client code.

Classes included in the pattern

-Facade: It knows the specific functions of each class in the subsystem, and converts client requests into calls to internal objects in the system. -System internal classes (ComplicatedClass): These classes will implement system functions and handle various tasks assigned to objects on the facade. They themselves do not know the existence of the facade layer, nor do they make any reference to it.

UML diagram

Functions and application scenarios

-Want to provide a simple interface for a complex subsystem. Subsystems tend to become more and more complex with their own development. Most of the design patterns they apply will result in more classes and smaller code segments. This makes the subsystem more reusable and easier to customize. For some clients that cannot be customized, it also becomes difficult to use. The facade layer can provide a simplified calling interface that is good enough for most clients. Only a few highly customized clients need to directly call the underlying code behind the facade layer. -There are a lot of dependencies between the client and the implementation classes of the abstraction layer. The introduction of a facade layer can decouple the client's subsystems from other subsystems, thereby promoting the independence and portability of the subsystems. -You want to add levels to your subsystem. Use a facade layer to define an entry point for each subsystem level. If there are dependencies between subsystems, then you can simplify the mutual dependencies by making all interactions between these subsystems go through the facade layer.

Agency design pattern

According to different purposes, there are various types of agents. For example, there are protective agents that control access to an object; there are virtual agents that deal with objects that are too expensive to create and access remote objects through remote access control.

Classes included in the pattern

UML diagram

Functions and application scenarios

The proxy mode is mainly used when we need to use a simple object to represent a complex object. If the cost of creating an object is high, you can postpone its creation and use a simple object to proxy its function until it must be created immediately. This simple object can be called a proxy for a complex object.

Flyweight design pattern

Flyweight mode can reduce the cost of creating and operating a large number of similar fragmented objects. Flyweight mode is mainly used when a large number of objects of similar nature need to be created. A large number of objects consume high memory. The Flyweight model provides a solution, which is to reduce the memory load by sharing objects. Its specific implementation is to divide objects into two types according to their properties: intrinsic state and extrinsic state. Sharing is the key to the Flyweight model.

Classes included in the pattern

-The abstract flyweight declares an interface that must be implemented for the specific flyweight, and the extrinsic state is passed in through this method in the form of parameters. -Concrete Flyweight implements the Flyweight mode interface and stores the intrinsic state. The specific flyweight role must be shared. The specific flyweight role must keep its intrinsic state unchanged and be able to manipulate the extrinsic state. -The FlyweightFactory role (FlyweightFactory) is responsible for creating and managing the Flyweight Factory. In addition, the factory ensures the sharing of Flyweight roles. The factory maintains different flyweight object pools and is responsible for returning objects from the object pool and adding objects to the object pool when the object creation is complete. -The client maintains references to all flyweight objects, and needs to store and calculate the corresponding extrinsic state.

UML diagram

Functions and application scenarios

When we choose the Flyweight model, we need to consider the following factors:
-When a large number of objects need to be created. -Due to the large number of objects, memory overhead is a limiting factor. -Most object attributes can be divided into intrinsic state and extrinsic state. -The application needs to use multiple objects, and the objects need to be reused many times after they are created. -The extrinsic state is best obtained by calculation and does not need to be stored.

Behavioral model

Behavioral patterns are a type of design pattern that focuses on communication (interaction) between objects. The interaction between these objects can not only ensure that the objects can exchange data, while still maintaining loose coupling between the objects. Tight coupling generally occurs between a group of closely related (interdependent) classes. In the process of object-oriented design, the number of coupling references is directly proportional to the interdependence between classes in the design process. In layman's terms, when a class changes, how many other classes may need to be modified at the same time? Loose coupling is the key to software architecture design. In the behavioral model, the function implementation and the client that calls the implementation should be loosely coupled to avoid hard coding and dependencies. The behavioral model deals with the communication relationship between different objects, provides a basic communication method for it, and provides the most commonly used and most flexible solution to realize this communication method. Behavioral patterns describe not only the patterns of classes or objects, but also the communication patterns between them. Behavioral patterns can be used to avoid hard coding and dependencies. Behavior-based models are further divided into the following subcategories:
  1. Object behavior model: The object behavior model uses object composition instead of inheritance. Describe how a group of objects cooperate to perform some tasks, but a single object cannot perform these tasks.
  2. Class behavior model: The class behavior model uses inheritance rather than object composition to describe algorithms and process control.
Specifically include:
-Chain of Responsibility (COR): A method of passing requests between a series of object chains. -Command mode: The command mode is mainly used when a request needs to be made to an object. The requesting object does not need to know the operation content of the request, nor the actual recipient of the request. -Interpreter mode: The interpreter provides a way to use a specific language in the code. The interpreter pattern is a design pattern used to parse a specific language in a program. -Iterator mode: Iterators are used to sequentially access the elements in a collection (combination) object without having to understand its internal structure. -Mediator pattern: define simple inter-class communication. -Memo mode: capture and restore the internal state of the object. -Observer mode: a way to notify multiple classes of changes. -State mode: change the function of an object when its state changes. -Strategy mode: Encapsulate algorithms in classes. -Template method mode: Delay some steps in the algorithm to subclasses for calculation. -Visitor mode: Define a new operation for the class without changing the class.
Object Behavior ModelClass Behavior Model
Chain of Responsibility Model
Interpreter mode
Command ModeTemplate Method Mode
Iterator Mode
Intermediary Model
Memo Mode
Observer Mode
State Mode
Strategy Mode
Visitor Mode

Chain of Responsibility Design Pattern

In the chain of responsibility model, the sender sends a request to an object chain, and the objects in the chain handle the request by themselves. If an object in the chain decides not to respond to the request, it will forward the request to the next object in the chain. The purpose of the chain of responsibility is to decouple the sender and receiver of the request through a specific design. Decoupling is a very important aspect in software design. Through this design pattern, we can completely decouple the sender and receiver. The sender is the object used to invoke the operation, and the receiver is the object that receives the request and performs the related operation. Through decoupling, the sender does not need to care about the receiver's interface. In the chain of responsibility model, responsibilities are passed back and forth. For the objects in the chain, the responsibility for deciding who will respond to the request is borne by the objects on the left in the entire chain. It's like passing questions in a question-and-answer quiz. When the asker asks a person a question, if he does not know the answer, he passes the question to the next individuals, and so on. When a person answers the question, the question stops passing down. Sometimes, when the last person is reached, no one can answer the question. We can cite several examples of chain of responsibility patterns: coin sorters, ATM machines, Servlet filters, and Java exception handling mechanisms. In Java, we can throw an exception when the exception sequence is listed in the catch statement, and the catch list scans one by one from top to bottom. If you catch up with the first exception handling, you can complete the task immediately, otherwise the responsibility will be transferred to the next line until the last line.

Classes included in the pattern

-Abstract Handler (Handler): Defines the interface used to process the request. -Concrete Handler: It is responsible for processing requests. If it can handle such a request, it will handle it itself, otherwise it will send the request to the next processor. -Client: Send the command to the first object in the chain of responsibility that can handle the request.

UML diagram

Functions and application scenarios

-The sender does not know which object in the chain will respond to the request. -Each object in the responsibility chain is responsible for deciding whether to respond to the request, and if these objects are capable of responding to the request, they will respond to the request. -If the object (or node) decides to pass the request backwards, it needs to have the ability to select the next node and continue the pass. -It is also possible that no node can respond to the request (some requests may not be processed) -It is determined at runtime which objects can respond to the request.

Command design pattern

Command mode (also called action mode, business mode) is an object behavior mode. This allows us to achieve complete decoupling between sender and receiver. The sender is the object that invokes the operation, and the receiver is the object that receives the request and performs a specific operation. Through decoupling, the sender does not need to understand the receiver's interface. Here, the meaning of the request is the command that needs to be executed.

Classes included in the pattern

-Abstract command class (Command): declare the command interface that needs to be executed in the class. -Concrete Command Class (ConcreteCommand): binds the recipient object and the behavior. It implements the execute method by calling the corresponding operation in the receiver. -Client: The client completes the instantiation of the command object and provides information about the method that needs to be called subsequently. -Invoker: The caller decides the appropriate method of invocation. -Receiver: A receiver is an instance of a class that contains method code. This means that it knows how to process a request and perform the corresponding actions. Any class can be used as a receiver.

UML diagram

Functions and application scenarios

-Realize function execution through parameterized objects. Commands are object-oriented rather than callback functional. -Specify the message queue and execute the request at different times. A command object can have a life cycle independent of the original request. If the recipient of a request can be represented by an independent address space, then you can convert the command object corresponding to the request to a different process and complete the request in it. -Support cancellation. The execution of the command can be stored as a state, and the command can be cancelled when needed. The command interface must add an unexecute operation to support the cancellation of the execution effect of the previous command call. The executed commands are stored in the command history list. Unlimited undo and redo are achieved by traversing this list and calling unexecute and execute respectively. -Support logging changes, allowing commands to be reapplied in the event of a system crash. By adding load and store operation command interface parameters, you can save a continuously changing log. Recovering from a system crash requires reloading the log commands from the disk and using Execute to re-execute these commands. -Build a system through high-level operations based on native operations. Such a structure is very common in information systems that support trading operations. A transaction transaction encapsulates a set of changing data. The command mode provides a trading model. Commands have a common interface, allowing you to call all transactions in the same way. This model also makes it easy to interact and expand with new trading systems.
Precautions:
-Purpose: Encapsulate the request as an object, so that the client can parameterize different requests, queues, log requests, and other operations that support cancellation.
-The requesting object does not need to know the operation corresponding to the request or any information about the recipient of the request.
  • as a result of: -Decouple the command between the object that invokes the operation and the object that performs the operation. That is, the decoupling between the caller and the receiver. -The command is converted to a class of objects. It can be manipulated and extended like other objects. -We can combine commands into a combined command. Generally speaking, a combination command is an example of a combination mode. -It's easy to add new commands, because we don't need to change existing classes.

Interpreter design pattern

The interpreter mode is a design mode used to parse a specific grammar in a program. The interpreter mode is an application of the combined mode. For a specific language, the interpreter mode can define an interpreter for its grammatical representation, and realize the translation and interpretation of the language sentence.

Classes included in the pattern

-Context: Contains global information about the interpreter -Expression (AbstractExpression): An abstract class with an abstract method called interpret. It declares the interface to perform the operation. -Terminal Expression (TerminalExpression): is an expression with a terminal symbol. -Nonterminal Expression (NonterminalExpression): an expression that implements a logical operation (and or operation) between two terminal expressions or nonterminal expressions. -Client: Build an abstract tree and call the interpret method in the abstract tree.

UML diagram

Functions and application scenarios

The scope of application of the interpreter mode is very limited. We can say that the interpreter mode is only used where formal grammar interpretation is required, but these areas often have better standard solutions, so in actual use, this mode is not often used. This mode can be used to interpret expressions that use a specific syntax or to build a simple rule engine.

Iterator design pattern

The iterator pattern is also a behavioral pattern. The iterator pattern allows traversal (also called collection) of a set of object elements to complete the function.

Classes included in the pattern

-Iterator: It will implement an abstract iterator interface for defining iterators. -Concrete iterator (Concretel): This is the implementation of the iterator (implements the iterator interface). -Abstract container (Container): This is the interface used to define the aggregation relationship. -Concrete Container (ConcreteContainer): the realization of an aggregation relationship.

UML diagram

Functions and application scenarios

-Need to access the content of an aggregate (also known as container) object without knowing its internal representation. - -Support multiple traversal methods for aggregated objects. -Provide a unified interface for traversing different aggregation structures (that is, support polymorphic iteration). -The iterator mode allows us to access the contents of the collection object without exposing its internal data structure. -Support multiple iterators to traverse collection objects at the same time. This means that we can create multiple independent iterators for the same collection. -Provide a unified interface for traversing different collections.

Intermediary design pattern

The intermediary pattern is mainly about the design pattern of data interaction. The intermediary design pattern is easy to understand, but difficult to implement. The core of the model is an intermediary object, responsible for coordinating a series of different data requests between a series of objects. This series of objects is called a colleague class. The colleague class will let the intermediary know that they will change so that the intermediary is responsible for dealing with the impact of changes on the interaction between different objects.

Classes included in the pattern

-Mediator interface (Mediator): It defines an interface to realize communication between colleague objects. -ConcreteMediator: It knows all colleague classes and keeps mutual references with these colleague classes. It realizes the communication and message transfer with colleagues. -Colleague classes (Colleague): These classes hold references to intermediaries. Whether they want to interact with any other colleague class, they must communicate with the intermediary class.

UML diagram

Functions and application scenarios

-A group of objects uses standard communication methods, but the overall communication connection is very complicated. The resulting interdependence makes the system difficult to structure and understand. -Due to the communication and mutual references between objects, it is difficult to reuse objects. -The behaviors distributed in multiple classes can be customized uniformly without creating too many subclasses.
Problems to be aware of: When actually using the intermediary model, it will make the problem more and more complicated. So the best practice is to only let the intermediary class be responsible for the communication part between objects.
-Define an object to be responsible for the interaction between a series of objects. -Colleagues send and receive requests through an intermediary.
Features:
-It decouples the colleague class. The intermediary class implements loose coupling between colleague classes. You can modify and reuse different colleague classes independently of each other. -It simplifies the object agreement. The intermediary replaces many interactions and realizes one-to-many communication with multiple colleagues. One-to-many relationships are easier to understand, maintain, and expand. -It centralized control. The intermediary model integrates the complexity of system interaction in the intermediary. Therefore, after the protocol is encapsulated through an intermediary, it will be more complicated than any single colleague class. This makes the intermediary as a whole difficult to maintain. -Facade mode is different from the intermediary mode in that it abstracts the subsystem of the object to provide a more convenient interface. This kind of abstraction is one-way. In other words, the facade object will send requests to the various classes in the subsystem, but not vice versa. In contrast, the intermediary model is more like the cooperative behavior between colleague objects through the intermediary, and the interaction of the system is multi-directional. -When each colleague class only interacts with one intermediary object, there is no need to define an abstract intermediary class. Abstract mediators are only used when multiple colleague classes interact through multiple abstract mediator subclasses, and vice versa.

Memo design pattern

We will use this mode at least once a day. The memo mode provides the ability to restore the object to its previous state (undo by rollback). The memo mode is realized by two objects: initiator and manager. The initiator is an object with internal state. The manager will perform some operations on the initiator, And realize the undo changes.

Classes included in the pattern

-Originator: The originator knows how to save himself. This is the class we want to save the state. -Caretaker: The manager is the object used to manage the initiator to save the state, specifically dealing with when, how, and why the initiator stores the state. The administrator should be able to make changes to the initiator and at the same time be able to undo these changes. -Memento: Memento will save the status information of the initiator, and these statuses cannot be modified by the manager.

UML diagram

Functions and application scenarios

When we need to provide a revocation mechanism in practical applications, when an object may need to restore its internal state in subsequent operations, we need to use the memo mode. Combining this design pattern to implement object state serialization can make it easy to save the object state and perform state rollback. When a snapshot of the state of an object must be stored and needs to be restored during subsequent operations, the memo mode can be used.

Observer Design Pattern

In the observer mode, an object called the observed maintains a collection of observer objects. When the observed object changes, it will notify the observer. Observers can be added or deleted from the set of observers maintained by the observed object. The state change of the observed person can be transmitted to the observer. In this way, the observer can make corresponding changes according to the state of the observer.

Classes included in the pattern

-Listener: Defines the interface or abstract class for adding and removing observer operations to the client. -Specific Observed (ConcreteListener): Specific Observed Class. It maintains the state of the object and notifies observers when its state changes. -Observer: Defines the interface or abstract class used to notify the object. -Concrete Observer (ConcreteObserver): Concrete Observer is implemented.

UML diagram

Functions and application scenarios

-When the change of an object requires other objects to change at the same time, and we don't know how many objects need to be changed together. -When an object must notify other objects without knowing who these objects are. -When an abstraction contains two aspects, one of which depends on the other. Encapsulate these aspects into independent objects so that we can change and reuse them independently.

State design pattern

State mode is a behavioral mode. The idea behind the state pattern is to change the behavior of the object according to its state change. The state mode allows objects to implement different behaviors based on their internal state (content class). The content class can have a large number of internal states. Whenever the request method is called on the content class, the message is delegated to the state class for processing. The state class interface defines a general interface that is valid for all specific state classes, and encapsulates all operations related to a specific state in it. Specific status classes provide specific implementations for requests. When the state of the content class changes, the specific state class associated with it will also change accordingly.

Classes included in the pattern

-Content class (Context): The content class is mainly used for the client of the state mode. The client does not directly access the state of the object. The content class has a specific state object and provides the required behavior according to its current state. -Abstract state class (State): This abstract class is the base class of all concrete state classes. The state class defines a common interface. Content class objects can realize changes to different functions by using this interface. There is no state in each item or attribute of the state class and its subclasses. -Concrete State class (ConcreteState): The concrete state class implements real functional changes according to the state provided by the content class. The behaviors provided by each state class are applicable to a certain state of the content class object. They also contain the instructions issued by the content state changes.

UML diagram

Functions and application scenarios

-The state mode provides a clear state representation for the object. -It allows an object to partially and clearly change its type at runtime.

Strategy Design Pattern

The strategy mode is mainly used when different algorithms need to be used to process different data (objects). This means that the strategy pattern defines a series of algorithms and makes them interchangeable. Strategy mode is a design mode in which algorithms can be selected at runtime. This mode can make the algorithm independent of the client that calls the algorithm. Strategy mode is also called policy mode. The strategy mode can be used when using a variety of different algorithms (each algorithm can correspond to a separate class, and each class has different functions).

Classes included in the pattern

-Abstract strategy class (Strategy): Define a common interface supported by all algorithms. The content class will use this interface to call the algorithms defined by the specific strategy class. -Concrete strategy class (ContreteStrategy): Each concrete strategy class will implement a corresponding algorithm. -Context: Contains a reference to the policy object. It can define an interface for the strategy class to access content class data. The content class object contains a reference to the specific policy object to be used. When a specific operation needs to be performed, the corresponding algorithm will be run from the corresponding strategy class object. The content category itself is not aware of the execution of the strategy category. If necessary, you can also define a dedicated object to transfer data from the content class object to the strategy class. The content class object receives the request from the client and delegates it to the strategy class object. Usually the specific strategy class is created by the client and passed to the content class. From this point of view, the client only interacts with the content class.

UML diagram

Functions and application scenarios

When we have a variety of different algorithms to choose from (each algorithm can correspond to a separate class, and the function of each class is different), the strategy pattern can be applied. The strategy mode defines a set of algorithms and enables them to be used interchangeably.

Template method design pattern

The template method defines the various execution steps of the algorithm. One or more steps of the algorithm can be implemented by subclasses through rewriting, while ensuring the integrity of the algorithm and being able to achieve multiple different functions. The class behavior pattern uses inheritance to implement the function of the pattern. In the template method mode, there will be a method (Template method method) to define the various steps of the algorithm. The specific implementation of these steps (ie methods) will be placed in subclasses. In other words, a specific algorithm is defined in the template method, but the specific steps of the algorithm still need to be defined by subclasses. The template method will be implemented by an abstract class. In this abstract class, the various steps (methods) of the algorithm will be declared, and finally the method declaration of its concrete implementation will be implemented as a subclass of the abstract class.

Classes included in the pattern

-Abstract Class (AbstractClass): Defines the abstract operations of the algorithm, and assigns specific subclasses to complete the specific implementation of these operations. It implements a template method, which contains the steps of the algorithm. The template method also defines the basic operations of each corresponding step in the abstract class. -Concrete Class (ConcreteClass): They implement the specific steps of the algorithm class by performing basic operations. When a specific class is called, the template method code is executed from the base class, and the various methods used by the template method are implemented and invoked by the derived class.

UML diagram

Functions and application scenarios

Application scenario:
-When the function of an algorithm needs to be able to change, this change is achieved by rewriting the function in the subclass. -When we want to avoid code duplication, we can implement different changes in algorithms in subclasses. -In the beginning, the template approach may not be an obvious choice. The most obvious phenomenon will be when we find that almost identical classes are performing some similar logic. At this time, we should consider using the template method pattern to clean up the existing code.

Visitor Design Pattern

The visitor mode is used to simplify the grouping of object-related operations. These operations are performed by the visitor, rather than putting the code in the accessed class. Since the access operation is performed by the visitor, not by the accessed class, the code that performs the operation will be concentrated in the visitor, rather than scattered in the object group. This provides better maintainability for the code. The visitor pattern also avoids using the instanceof operator to perform calculations on similar classes.

Classes included in the pattern

-Visitor (Visitor): includes an interface or abstract class used to declare which operations are accessed in all types of accessible objects. Usually the names of operations are the same, but different operations are distinguished by the parameters of the method. The input object type determines which of the methods to access. -Concrete Visitor: Used to implement various types of visitors and various types of access methods. It is declared in the abstract visitor and is implemented independently of each other. Each specific visitor will be responsible for implementing different functions. When defining a new visitor, you only need to pass it to the object structure. -Element class (Element): An abstract object is used to declare accepted operations. It is an entry point, which types of visitor objects can be allowed to access. Each object in the collection needs to implement the abstract object so that the corresponding visitor can access it. -Concrete Element: These classes implement the interface or class of the abstract element class and define the accepted operations. Through its acceptable operations, the visitor object can be passed to the object. -ObjectStruture: This is a class that contains all accessible objects. It provides a mechanism to traverse all elements. This structure is not necessarily a collection, but can also be an extremely complex structure, such as a composite object.

UML diagram

Functions and application scenarios

In the visitCollection() method, we call Visitable.accept(this) to implement the call to the correct visitor method. This is called double assignment. The visitor calls the method in the element class, and then returns to call the visitor class. Mode problem: In the case of using the visitor model, if you want to add a new specific element Element (data structure) will be more difficult. Adding a ConcreteElement involves adding new operations to the visitor interface and adding corresponding implementations in each specific visitor implementation. Visitor mode is more suitable when the object structure is very stable, but the operation of the object needs to be changed frequently. The visitor pattern only provides methods for handling each data type, and lets the data object determine which method to call. Since the data object essentially knows its own type, the function of the algorithm in the visitor pattern to determine the method to be called is trivial. Therefore, the overall processing of data includes the distribution of data objects and the secondary distribution through appropriate visitor processing methods. This is called double assignment. One of the main advantages of using the visitor pattern is that it is very easy to add new operations that need to be performed in our data structure. All we have to do is to create a new visitor and define the corresponding actions. The main problem with the visitor pattern is that because each visitor needs to have a corresponding method to deal with every possible specific data, once the visitor pattern is implemented, the number and types of its specific classes cannot be easily changed.

Comments(0)

Continue with
to comment