Design pattern usage scenarios

classification

Creation type: singleton pattern, simple factory pattern, factory method pattern, abstract factory pattern

Structural type: Agency model

Behavioral: Observer Mode

Introduction

Singleton mode

**Definition:** Ensure that a class has only one instance, and provide a global access point to access it.

Structure diagram:
Insert picture description here
Advantages:

  • Achieved controllable access to the unique instance
  • For some objects that need to be created and destroyed frequently, the performance of the system can be improved

Disadvantages:

  • It is not suitable for changing objects. If objects of the same type always change in different use case scenarios, singletons will cause data errors and cannot save each other's state.
  • There is no abstraction layer, which is not conducive to expansion
  • Excessive responsibilities, violating the principle of single responsibility

scenes to be used:

  • In the case of resource sharing, avoid performance or loss caused by resource operation. As in the above log file (always open, because there can only be one instance to operate, otherwise the content is not easy to add), apply the configuration.
  • In the case of controlling resources, it is convenient to communicate between resources. Such as thread pool and so on.

Observer mode

**Definition:** defines a one-to-many dependency relationship, allowing multiple observer objects to monitor a certain subject object at the same time. This subject object will notify all observer objects when the state changes, so that they can update themselves automatically.

structure:
Insert picture description here

  • Subject: Abstract theme (abstract observer). The abstract theme role stores all observer objects in a collection. Each theme can have any number of observers. The abstract theme provides an interface to add and delete observer objects.
  • ConcreteSubject: Specific topic (specific observer), this role saves the relevant state into the specific observer object, and sends a notification to all registered observers when the internal state of the specific topic changes.
  • Observer: Abstract Observer is an abstract class of Observer. It defines an update interface to update itself when notified of a theme change.
  • ConcrereObserver: A specific observer, which implements the update interface defined by the abstract observer, so that it can update its own state when notified of a theme change.

scenes to be used:

  • In the context of association behavior, it should be noted that the association behavior is separable, not a "combined" relationship.
  • Multi-level events trigger scenes.
  • Cross-system message exchange scenarios, such as the processing mechanism of message queues and event buses.

**Advantages:** Decoupling , so that both sides of the coupling rely on abstraction, so that their respective transformations will not affect the transformation on the other side.

Disadvantages: When applying the observer mode, you need to consider the issues of development efficiency and operating efficiency . The program includes one observer and multiple observers. The development and debugging content will be more complicated, and the notification of messages in Java is generally Sequential execution, then an observer stuck, will affect the overall execution efficiency, in this case, generally use asynchronous implementation.

Agency model

**Definition:** Provide a proxy for other objects to control access to this object. (Purchasing, litigation)

structure:
Insert picture description here

  • Subject: An abstract subject class that declares the common interface method of the real subject and the agent.
  • RealSubject: The real subject class defines the real object represented by the proxy. The client indirectly calls the methods of the real subject class through the proxy class.
  • ProxySubject: The proxy class holds a reference to the real subject class, and calls the corresponding interface method in the real subject class in the interface methods it implements.
  • Client: Client class.

**Implementation: **The proxy class contains the real subject class (delegated), and the final call is the method implemented by the real subject class (delegated)

Types of:

  • Remote proxy: Provide a local representation for an object in different address spaces, so that the system can hide the server part of the matter .
  • Virtual agent: Use a proxy object to represent a very resource-intensive object and create it when it is really needed.
  • Security proxy: used to control the access rights of real objects .
  • Smart guidance: When calling a real object, the agent handles other things, such as calculating the reference count of the real object , and when the object is not referenced, it can automatically release it; or when accessing a real object, check whether it can be locked, To ensure that other objects cannot change it.

**Usage scenario: **When you can't or don't want to directly access an object, you can indirectly access it through a proxy object.

Simple factory pattern

**Definition:** Define a class to be responsible for creating instances of other classes. The created instances usually have a common parent class

structure:
Insert picture description here

advantage:

  • Allows users to obtain corresponding class instances according to parameters, avoiding direct instantiation of classes and reducing coupling.

Disadvantages:

  • The factory class concentrates the creation logic of all instances (products). Once the factory fails to work normally, the entire system will be affected;
  • Violating the "open-close principle", once a new product is added, the factory logic has to be modified, which will cause the factory logic to be too complicated.
  • Because the simple factory model uses static factory methods, static methods cannot be inherited or rewritten, which will cause the factory role to fail to form a hierarchy based on inheritance.

scenes to be used:

  • The factory class is responsible for creating fewer objects.
  • The customer only knows the parameters passed into the factory class, and does not care about how to create the object (logic).

Factory method pattern

**Definition:** Define an interface for creating objects, let the subclass decide which class to instantiate, and delay the instantiation of a class to its subclass

Structure:
Insert picture description here
Advantages:

  • It is more in line with the open-close principle. When adding a new product, you only need to add the corresponding specific product category and the corresponding factory sub-category.
  • In line with the principle of single responsibility, each specific factory class is only responsible for creating corresponding products
  • Do not use static factory methods, can form a hierarchy based on inheritance

Disadvantages:

  • When adding new products, in addition to adding new product categories, the corresponding specific factory categories must also be provided. The number of system categories will increase in pairs, which increases the complexity of the system to a certain extent; at the same time, there are more categories. Need to compile and run, will bring some additional overhead to the system;
  • Considering the scalability of the system, an abstraction layer needs to be introduced, and the abstraction layer is used for definition in the client code, which increases the abstraction and difficulty of understanding the system, and may need to use DOM, reflection and other technologies in implementation. Increased the difficulty of system implementation.
  • Although it is guaranteed that the modification in the factory method is closed, for the class that uses the factory method, if you want to replace another product, you still need to modify the instantiated concrete factory class;
  • A specific factory can only create one specific product

scenes to be used:

  • When a class does not know the class of the object it needs. In the factory method pattern, the client does not need to know the class name of the specific product category, only the corresponding factory;
  • When a class wants to specify the creation of objects through its subclasses. In the factory method pattern, the abstract factory class only needs to provide an interface to create a product, and its subclasses determine the specific objects to be created, using object-oriented polymorphism and the principle of Richter's substitution, when the program is running , The subclass object will overwrite the parent object, thus making the system easier to expand.
  • The task of creating an object is delegated to one of the multiple factory subclasses. The client does not need to care about which factory subclass to create the product subclass when using it. It can be dynamically specified when needed, and the class name of the specific factory class can be assigned Stored in a configuration file or database.

Abstract factory pattern

**Definition:** Provide an interface to create a series of related or interdependent objects without specifying their specific classes

Structure:
Insert picture description here
**Advantages:** The process of creating an instance of a specific class is separated from the client. The client manipulates the instance through the abstract interface of the factory, and the client does not know who the specific implementation is.

**Disadvantages:** If you add a new product family, you also need to modify the abstract factory and all the concrete factories.

scenes to be used:

  • A system does not depend on the details of how product line instances are created, assembled, and expressed.
  • There are more than one product lines in the system, and only one of them is used at a time.
  • A product line (or a group of unrelated objects) has the same constraints.

**Note: **When there is only one product, the abstract factory mode becomes the factory mode. When the products of the factory mode become multiple, the factory mode becomes the abstract factory mode.

Strategy mode

motivation:

  • There are often many different ways to complete a task. Each way is called a strategy. We can choose different strategies to complete the task according to the environment or conditions.
  • Similar situations are often encountered in software development. There are multiple ways to achieve a certain function. At this time, a design pattern can be used to enable the system to flexibly select solutions, and it is also convenient to add new solutions.

**Definition:** Define a series of algorithms, encapsulate each algorithm, and make them interchangeable.

UML graphics:

  • Context: Environmental
  • Strategy: Abstract strategy class
  • ConcreteStrategy: Specific strategies

Insert picture description here

State mode

**Definition:** Allows an object to change its behavior when its internal state changes. The object seems to modify its class. The behavior of an object depends on its state, and its related behavior can be changed according to its state changes.

UML graphics:

  • Context: Environment class

  • State: abstract state class

  • ConcreteState: specific state class

Insert picture description here

Observer mode

**Definition:** Defines a one-to-many dependency relationship between objects. When the state of an object changes, all objects that depend on it are notified and automatically updated.

UML graphics:

Insert picture description here

Intermediary model

**Intent:** Use an intermediary object to encapsulate a series of object interactions. The intermediary makes the objects do not need to explicitly refer to each other, so that the coupling is loose, and the interaction between them can be changed independently.

**Main solution: **There are a lot of associations between objects and objects, which will inevitably lead to the structure of the system becoming very complicated. At the same time, if an object changes, we also need to track the objects associated with it, and do Appropriate treatment.

**When to use: **Multiple classes are coupled with each other to form a network structure.

**How ​​to solve:** Separate the above mesh structure into a star structure.

**Implementation:** We demonstrate the intermediary mode through a chat room example. In an example, multiple users can send messages to a chat room, and the chat room displays messages to all users. We will create two classes ChatRoom and User . User objects use the ChatRoom method to share their messages.

Adapter mode

**Intent:** To convert the interface of a class into another interface that the customer wants. The adapter pattern allows classes that cannot work together because of interface incompatibility to work together.

**Main solution: **The main solution is that in software systems, some "existing objects" are often placed in a new environment, and the interfaces required by the new environment cannot be met by the existing objects.

Bridge mode

**Intent:** Separate the abstract part from the implementation part so that they can be changed independently.

**Main solution: **In a variety of situations that may change, using inheritance will cause class explosion problems, and it is not flexible to expand.

Decorator mode

**Intent:** To dynamically add some additional responsibilities to an object. In terms of increasing functionality, the decorator pattern is more flexible than generating subclasses.

**Main solution: **Generally, we often use inheritance in order to extend a class. Because inheritance introduces static characteristics to the class, and with the increase of extended functions, the subclass will be very swollen.

**When to use: **Extend a class without adding many subclasses.

Insert picture description here

Agency model

**Definition: ** In some cases, a client does not want or cannot directly refer to an object. In this case, a third party called "agent" can be used to achieve indirect reference. The proxy object can act as an intermediary between the client and the target object, and can remove content and services that the client cannot see or add additional services that the client needs through the proxy object.

UML graphics:
Insert picture description here

Guess you like

Origin blog.csdn.net/WuLex/article/details/113481748