Today we are going to learn a behavioral Pattern, Strategy Pattern.

The schema definition

Define a series of algorithms, encapsulate each one, and make them interchangeable. A Policy pattern, also known as a Policy pattern, allows an algorithm to change independently of the customers that use it.

The model structure

The policy mode contains the following roles:

Context: Context: abstract Strategy: ConcreteStrategy: ConcreteStrategy

UML diagrams

Code implementation

Generally, if a problem has multiple solutions or slightly different operations, the simplest way is to use if-else or switch-case to solve the problem. For simple solutions, this is undoubtedly simple, convenient and fast. However, if the solution includes a large amount of processing logic that needs to be encapsulated, Or when the processing mode changes greatly, it will appear chaotic and complex, and the strategy mode is a good solution to this problem, it separates all kinds of programs, so that the operator can dynamically choose different strategies according to the specific needs. Simple calculation operations (+, -, *, /) are used as examples:

UML diagrams

Strategy.java

/** * Public interface Strategy {double calc(double paramA, double paramB); }Copy the code

AddStrategy.java

Public implements Strategy {@override public implements Strategy {@override public implements Strategy () {@override public implements Strategy (); double paramB) { System.out.println("Execute AddStrategy");
        return paramA + paramB;
    }}Copy the code

SubStrategy.java

Public implements Strategy {@override public implements Strategy {@override public implements Strategy {@override public implements Strategy {@override public implements Strategy; double paramB) { System.out.println("Execute SubStrategy"); 
             return paramA - paramB;   
 }}Copy the code

MultiStrategy.java

Public implements Strategy {@override public implements Strategy {@override public implements Strategy (implements Strategy) {@override public implements Strategy (implements Strategy); double paramB) { System.out.println("Execute MultiStrategy");  
      return paramA * paramB;   
 }}Copy the code

DivStrategy.java

/ /public class DivStrategy implements Strategy {@override public implements Strategy (double paramA, double paramB) { System.out.println("Execute DivStrategy");  if (paramB == 0) { throw new IllegalArgumentException("Cannot divide into 0");  }  return paramA / paramB; }}Copy the code


Calc.java

/** * public class Calc {private Strategy mStrategy; public voidsetStrategy(Strategy strategy) {    
    this.mStrategy = strategy;  
  }  
  public double calc(double paramA, double paramB) { 
       if (mStrategy == null) {  
          throw new IllegalStateException("You haven't set the strategy for computing.");      
  } 
       return mStrategy.calc(paramA, paramB);   
 }}Copy the code

The test class

public class MyClass {

    public double calc(Strategy strategy, double paramA, double paramB) {
        Calc calc = new Calc();
        calc.setStrategy(strategy);
        return calc.calc(paramA, paramB);
    }

    public static void main(String[] args) {
        MyClass myClass = new MyClass();
        System.out.println("Calculation Add " + myClass.calc(new AddStrategy(), 10, 5));
        System.out.println("Calculation Add " + myClass.calc(new SubStrategy(), 10, 5));
        System.out.println("Calculation Add " + myClass.calc(new MultiStrategy(), 10, 5));
        System.out.println("Calculation Add "+ myClass.calc(new DivStrategy(), 10, 5)); }}Copy the code

The results

Pattern analysis

  • The strategy pattern is a design pattern that is easy to understand and use. The strategy pattern is the encapsulation of the algorithm, which separates the responsibility of the algorithm from the algorithm itself and delegates it to different objects to manage. Policy patterns usually encapsulate a set of algorithms into a set of policy classes as a subclass of an abstract policy class. In a word, “Prepare a set of algorithms and encapsulate each one so that they are interchangeable.”

  • In the policy pattern, it is up to the client to decide which specific policy roles to use in what situations.

  • Policy mode only encapsulates the algorithm, providing convenience for new algorithms to be inserted into the existing system and old algorithms to be “retired” from the system. Policy mode does not decide when and which algorithm to use. The algorithm selection is up to the client. This improves the flexibility of the system to some extent, but the client needs to understand the differences between all the specific policy classes in order to choose the appropriate algorithm, which is also one of the disadvantages of the policy pattern, which increases the difficulty for the client to use to some extent.

Advantages of the policy pattern

  • The policy pattern provides perfect support for the “open closed principle”, allowing users to choose algorithms or behaviors without modifying the existing system, or to flexibly add new ones.

  • The policy pattern provides a way to manage related algorithm families.

  • The policy pattern provides an alternative to inheritance.

  • Use policy patterns to avoid multiple conditional transition statements.

Disadvantages of the policy pattern

  • The client must know all the policy classes and decide which one to use.

  • The policy pattern will result in many policy classes.