This is the fifth day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021

In the Strategy Pattern, the behavior of a class or its algorithm can be changed at run time.

This type of design pattern is behavioral.

introduce

describe parsing
intentions Define a set of algorithms, encapsulate them one by one, and make them interchangeable.
Mainly to solve In cases where multiple algorithms are similar, use if… Else is complex and difficult to maintain.
When to use When a system has many similar classes, all that distinguishes them is the internal computational logic.
How to solve Encapsulate these algorithms into classes and replace them arbitrarily.
The key code Implement the same interface.
Examples of application 1. Add and subtract the two arrays in the calculator, replace the algorithm strategy, you can get different results. 2, the way to travel, choose to ride a bicycle, by car, each kind of travel is a strategy. LayoutManager in JAVA AWT.
advantages 1. The algorithm can be switched freely. 2. Avoid using multiple conditional judgments. 3,Good scalability.
disadvantages 1. Policy classes will increase. 2. All policy classes need to be exposed.
Usage scenarios 1. If there are many classes in a system that are distinguished only by their behavior, the use of the policy pattern dynamically allows an object to choose one behavior among many. A system needs to dynamically choose one of several algorithms. 3. If an object has a number of behaviors, without the appropriate pattern, those behaviors will have to use multiple conditional selection statements (if… Else).
Matters needing attention If a system has more than four policies, you need to consider using mixed mode to solve the problem of policy class inflation.

implementation

In the policy pattern, you create objects that represent various policies and a context object whose behavior changes as the policy object changes. The policy object changes the execution algorithm of the context object.

The example will simulate the addition, subtraction, and multiplication of two numbers. The following classes are needed:

1. Strategy interface class, define Strategy methods.

  • OperationAdd Add policy class;

  • OperationSubtract Strategy class;

  • The OperationMultiply policy class.

2. Context object, which stores the current policy.

3. StrategyPatternDemo scenario.

Step 1- Create the interface class

Create an interface.

// Strategy.java
public interface Strategy {
   public int doOperation(int num1, int num2);
}
Copy the code

Step 2- Implement the interface class

Create an entity class that implements the interface.

// OperationAdd.java public class OperationAdd implements Strategy{ @Override public int doOperation(int num1, int num2) { return num1 + num2; }}Copy the code
// OperationSubtract.java
public class OperationSubtract implements Strategy{
   @Override
   public int doOperation(int num1, int num2) {
      return num1 - num2;
   }
}
Copy the code
// OperationMultiply.java
public class OperationMultiply implements Strategy{
   @Override
   public int doOperation(int num1, int num2) {
      return num1 * num2;
   }
}
Copy the code

Step 3- CreateContextCurrent object storage policy

Create the Context class.

// Context.java public class Context { private Strategy strategy; public Context(Strategy strategy){ this.strategy = strategy; } public int executeStrategy(int num1, int num2){ return strategy.doOperation(num1, num2); }}Copy the code

Step 4- Build the scenario class

Create the scenario class StrategyPatternDemo.

// StrategyPatternDemo.java public class StrategyPatternDemo { public static void main(String[] args) { Context context = new Context(new OperationAdd()); System.out.println("10 + 5 = " + context.executeStrategy(10, 5)); context = new Context(new OperationSubtract()); System.out.println("10 - 5 = " + context.executeStrategy(10, 5)); context = new Context(new OperationMultiply()); System.out.println("10 * 5 = " + context.executeStrategy(10, 5)); }}Copy the code

Step 5- Print out

Execute the program and output the result:

10 plus 5 is 15. 10 minus 5 is 5. 10 times 5 is 50Copy the code