一、策略模式
public class StrategyContext {
Strategy strategy;
public StrategyContext(Strategy strategy) {
this.strategy = strategy;
}
/**
*
*/
public int context(int a, int b) {
return strategy.operator(a,b);
}
}
策略模式的核心为StrategyContext上下文类,持有strategy对象,在context完成操作。
测试类
public class StrategyContextTest {
public static void main(String[] args) {
Strategy strategy;
strategy = new OperationAdd();
StrategyContext strategyContext = new StrategyContext(strategy);
strategy.operator(5,2);
}
}
二、技术笔记
1、如何使用策略模式解决大量使用if else 或大量switch问题
策略模式+反射
策略模式后好像使用都还是要用if else来决定调用哪个类,所以在引入策略模式后,在上下文类还要增加反射。
public class StrategyContext {
Strategy strategy;
public StrategyContext(String type) throws Exception {
Class clazz = Class.forName(type);
this.strategy = (Strategy) clazz.newInstance();
}
/**
*
*/
public int context(int a, int b) {
return strategy.operator(a,b);
}
当然这里的type可以用个枚举来解决。感觉代价非常大是不是没必要,不过代码的可读性还是增强了。
源代码:
gitee.com