Design Pattern (22) Strategy Pattern

Strategy Pattern

1. What is the strategy mode

Strategy Pattern: Define a series of algorithm classes, encapsulate each algorithm, and allow them to be replaced with each other. The strategy pattern allows the algorithm to change independently of the customers who use it. It is also called the policy pattern (Policy).
Strategy mode is an object behavior mode.

The main purpose of the strategy mode is to separate the definition and use of the algorithm, that is, separate the behavior of the algorithm from the environment, and place the definition of the algorithm in a special strategy class. Each strategy class encapsulates an implementation algorithm. The environment class is programmed for the abstract strategy class and conforms to the "dependency inversion principle". When a new algorithm appears, it is only necessary to add a new concrete strategy class that implements the abstract strategy class.

The strategy mode is the encapsulation of the algorithm, which separates the responsibility of the algorithm from the algorithm itself, and delegates to different object management. The strategy pattern usually encapsulates a series of algorithms into a series of concrete strategy classes as subclasses of abstract strategy classes.

In the strategy mode, the understanding of environment classes and abstract strategy classes is very important. Environment classes are classes that need to use algorithms. There can be multiple environment classes in a system, and they may need to reuse some of the same algorithms.

Strategy mode is used for free switching and expansion of algorithms, and it is one of the more widely used design modes.
The strategy mode corresponds to a family of algorithms to solve a certain problem, allowing users to choose an algorithm from the family of algorithms to solve a certain problem, and at the same time can easily replace the algorithm or add a new algorithm. As long as it involves algorithm encapsulation, multiplexing and switching, the strategy mode can be considered.

2. Role Analysis of Strategy Pattern

Structure diagram of strategy mode:
Strategy mode

  • Context (environmental class): The environment class is the role of the algorithm, it can use a variety of strategies when solving a certain problem (that is, implementing a certain method). Maintain a reference instance to the abstract strategy class in the environment class to define the strategy adopted.
  • Strategy (abstract strategy class): It declares abstract methods for the supported algorithms and is the parent class of all strategy classes. It can be an abstract class or a concrete class, or an interface. The environment class calls the algorithms implemented in the concrete strategy class at runtime through the methods declared in the abstract strategy class.
  • ConcreteStrategy (specific strategy class): It implements the algorithm declared in the abstract strategy class. At runtime, the concrete strategy class will override the abstract strategy class object defined in the environment class, and a specific algorithm is used to implement a certain business process .

3. Advantages and disadvantages of the strategy model

advantage:

  • The strategy mode provides perfect support for the "opening and closing principle". Users can select algorithms or behaviors without modifying the original system, or flexibly add new algorithms or behaviors.
  • Strategy mode provides a way to manage related algorithm families. The hierarchical structure of the strategy class defines an algorithm or behavior family, and the proper use of inheritance can move the common code to the abstract strategy class, thereby avoiding duplication of code.
  • The strategy mode provides a way to replace the inheritance relationship. If the strategy mode is not used, then the environment class that uses the algorithm may have some subclasses, and each subclass provides a different algorithm. However, in this way, the use of the algorithm is mixed with the algorithm itself, which does not conform to the "single responsibility principle". The logic of deciding which algorithm to use is mixed with the algorithm itself, making it impossible to evolve independently; and the use of inheritance cannot Realize the dynamic switching of algorithms or behaviors while the program is running.
  • Using strategy mode can avoid multiple conditional selection statements. Multiple conditional selection statements are not easy to maintain. It mixes the logic of which algorithm or behavior is adopted with the implementation logic of the algorithm or behavior itself, and hard-codes them all in a huge multiple conditional selection statement. The method of directly inheriting environment classes is primitive and backward.
  • The strategy mode provides an algorithm reuse mechanism. Since the algorithms are separately extracted and encapsulated in strategy classes, different environment classes can easily reuse these strategy classes.

Disadvantages:

  • The client must know all the strategy classes and decide which strategy class to use. This means that the client must understand the difference between these algorithms in order to select the appropriate algorithm in time. In other words, the strategy mode is only applicable when the client knows all the algorithms or behaviors.
  • The strategy mode will cause the system to produce many specific strategy classes, and any small changes will cause the system to add a new specific strategy class.
  • It is not possible to use multiple strategy classes on the client at the same time, that is, when using the strategy mode, the client can only use one strategy class at a time. It is not supported to use one strategy class to complete some functions and then use another strategy class to complete The remaining functions.

Applicable scene:

  • A system needs to dynamically select one of several algorithms, then these algorithms can be encapsulated into specific algorithm classes, and these specific algorithm classes are all subclasses of an abstract algorithm class. In other words, these specific algorithm classes all have a unified interface. According to the "Richteric Substitution Principle" and object-oriented polymorphism, the client can choose to use any specific algorithm class and only need to maintain one data type as an abstract algorithm class Object.
  • An object has many behaviors. If you don't use the appropriate mode, these behaviors can only be achieved using multiple conditional selection statements. At this point, using the strategy mode to transfer these behaviors to the corresponding specific strategy classes can avoid the use of multiple conditional selection statements that are difficult to maintain.
  • The client does not want to know the complex data structure related to the algorithm. Encapsulating the algorithm and related data structure in the specific strategy class can improve the confidentiality and security of the algorithm.

4. Practical impression

The purpose is clear and easy to understand.
The strategies do not know each other and do not communicate with each other.

5. Code example

// 抽象策略类
abstract class AbstractStrategy {
    
    
    public abstract void algorithm(); //声明抽象算法
}

// 具体策略类
class ConcreteStrategyA extends AbstractStrategy {
    
    
    //算法的具体实现
    public void algorithm() {
    
    
       //...
    }
}

// 环境类,使用算法的角色类
class Context {
    
    
    private AbstractStrategy strategy; //维持一个对抽象策略类的引用
 
    public void setStrategy(AbstractStrategy strategy) {
    
    
        this.strategy= strategy;
    }
 
    //调用策略类中的算法
    public void algorithm() {
    
    
        strategy.algorithm();
    }
}

// 测试
public static void main(String[] args) {
    
    
    Context context = new Context();
    AbstractStrategy strategy = new ConcreteStrategyA(); //可在运行时指定类型
    context.setStrategy(strategy);
    context.algorithm();
}

Guess you like

Origin blog.csdn.net/u014099894/article/details/85195212