Strategy Mode
1) basic definition
A class act or algorithm can be changed at run time, it is a pattern of behavior.
Intent: define a series of algorithms, encapsulate them, and make them interchangeable.
To solve the problem: Under a variety of algorithms similar case, if ... else brought complex and difficult to maintain
usage scenarios: a system has more than one class, and differentiate their direct their behavior just
how to solve: Scene represent respective strategies objects and object change a behavior change strategy as the context object policy object change point arithmetic context object.
The key code: implement the same interface
Class Diagram:
2.demo Code:
Policy Interface:
public interface Strategy {
public int doOperation(int num1,int num2);
}
Strategy interface class:
public class StrategyAdd implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1 + num2;
}
}
public class StrategyMultiply implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1 * num2;
}
}
Policy Context:
public class StrategyContex {
Strategy strategy;
public StrategyContex(Strategy strategy) {
this.strategy = strategy;
}
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public int executeStrategy(int num1,int num2) {
return strategy.doOperation(num1, num2);
}
}
Call demo:
public class StrategyDemo {
public static void main(String[] args) {
int num1 = 2,num2 = 3;
StrategyContex contextAdd = new StrategyContex(new StrategyAdd());
System.out.println(contextAdd.executeStrategy(num1, num2));
StrategyContex contextMultiply = new StrategyContex(new StrategyMultiply());
System.out.println(contextMultiply.executeStrategy(num1, num2));
System.out.println("*************");
contextMultiply.setStrategy(new StrategyAdd());
System.out.println(contextMultiply.executeStrategy(num1, num2));
}
}
Call demo output: