设计模式之策略模式和状态模式
程序员文章站
2022-06-17 17:15:50
...
1 策略模式
我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的 context 对象。策略对象改变 context 对象的执行算法,
我们可以简单理解为更加不同的策略对象,执行不同策略方法。
2 类图
3 代码实现
1)接口:Strategy.java
public interface Strategy {
public int doOperation(int num1, int num2);
}
2)实现类:OperationAdd.java
public class OperationAdd implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1 + num2;
}
}
3)实现类:OperationSubstract.java
public class OperationSubstract implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1 - num2;
}
}
4)实现类:OperationMultiply.java
public class OperationMultiply implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1 * num2;
}
}
5)创建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);
}
}
StrategyPatternDemo 里面的main函数
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 OperationSubstract());
System.out.println("10 - 5 = " + context.executeStrategy(10, 5));
context = new Context(new OperationMultiply());
System.out.println("10 * 5 = " + context.executeStrategy(10, 5));
}
}
4 运行结果
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
5 对比状态模式
我们上面策略模式里面的Demo里面每次都是通过传递新的策略对象来构建Context对象,那我们的状态模式可以理解为我们在Context类里面有单独设置策略对象的函数,不需要每次进行构建Context,状态模式是通过状态转移来改变 Context 所组合的 State 对象,而策略模式是通过 Context本身的决策来改变组合的 Strategy 对象
6 代码实现
我们把上面的Context里面的构造方法里面不要单独进行传递策略对象,我们单独增加一个SetStrategy这样的函数来设置策略改变当前类的策略对象具体的属性值。
Context.java
public class Context {
private Strategy strategy;
public Context(){
}
public SetStrategy(Strategy strategy){
this.strategy = strategy;
}
public int executeStrategy(int num1, int num2){
return strategy.doOperation(num1, num2);
}
}
public static void main(String[] args) {
Context context = new Context();
context.SetStrategy(new OperationAdd());
System.out.println("10 + 5 = " + context.executeStrategy(10, 5));
context.SetStrategy(new OperationSubstract());
System.out.println("10 - 5 = " + context.executeStrategy(10, 5));
context.SetStrategy(new OperationMultiply());
System.out.println("10 * 5 = " + context.executeStrategy(10, 5));
}
部分内容参考链接:https://www.runoob.com/design-pattern/state-pattern.html