策略模式简介
策略模式主要由这三个角色组成,环境角色(Context)、抽象策略角色(Strategy)和具体策略角色(ConcreteStrategy)。
环境角色(Context):持有一个策略类的引用,提供给客户端使用。
抽象策略角色(Strategy):这是一个抽象角色,通常由一个接口或抽象类实现。此角色给出所有的具体策略类所需的接口。
具体策略角色(ConcreteStrategy):包装了相关的算法或行为。
背景
所有具体的策略角色都以bean的形式存在于spring的容器中,我们需要一个实现环境角色(Context)来找到这些具体的策略角色,并执行
案例
输入到两个数字,根据策略做加减乘除操作
- 抽象策略
public interface Strategy {
public String type();
public int doOperation(int num1, int num2);
}
- 具体策略
//加:
public class OperationAdd implements Strategy{
@Override
public String type(){
return "+";
}
@Override
public int doOperation(int num1, int num2) {
return num1 + num2;
}
}
//减
public class OperationSubtract implements Strategy{
@Override
public String type(){
return "-";
}
@Override
public int doOperation(int num1, int num2) {
return num1 - num2;
}
}
/**略**/
- 环境角色
- 通过
ApplicationContextAware
接口获取到spring容器 - 在spring容器启动以后就将所有的具体策略纳入管理,应用生命周期勾子
SmartInitializingSingleton
@Component
public class OperationContext implements ApplicationContextAware, SmartInitializingSingleton {
private Map<String, Strategy> serviceMap;
private ApplicationContext applicationContext;
public int doOperation(String type,int num1,int num2) {
Strategy strategy= serviceMap.get(type);
if (strategy== null){
throw new BizException("getValidDataCount not found service : "+param.getModuleLabel());
}
return strategy.doOperation(num1,num2);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
在容器启动以后,找到所有的策略,并纳入管理
*/
@Override
public void afterSingletonsInstantiated(){
serviceMap = new HashMap<>();
Map<String, Strategy> beansOfType = this.applicationContext.getBeansOfType(Strategy.class);
beansOfType.values().forEach(x->{
serviceMap .put(x.type(), x);
});
}
}