定义一些列算法,然后把每一个算法封装起来,使它们可以相互替换。 实现:定义一个策略接口,每一个算法都去实现这个接口,然后定义一个上下文,持有接口的引用,然后客户端可以通过上下文获取到具体的策略
二、springmvc中的策略模式
前端控制器DispacherServlet
处理请求需要依赖很多组件类,如处理器映射HandlerMapping
,处理器适配器HandlerAdapter
,视图解析器ViewResolver
等,每种组件都有多种具体的实现,而DispcherServlet中只依赖组件的抽象接口。
三. spring中使用策略模式
1. 策略上下文 (比较关键的一点是AutoWired一个Map<String, Strategy> 这个会在初始化的时候将所有的Strategy自动加载到Map中,是不是很方便)
@Service
public class FactoryForStrategy {
@Autowired
Map<String, Strategy> strategys = new ConcurrentHashMap<>(3);
public Strategy getStrategy(String component) throws Exception{
Strategy strategy = strategys.get(component);
if(strategy == null) {
throw new RuntimeException("no strategy defined");
}
return strategy;
}
}
2. 策略接口
public interface Strategy {
String doOperation();
}
3. 策略实现类(Component里边的one是指定其名字,这个会作为key放到Map strategys里边)
@Component("one")
public class StrategyOne implements Strategy {
@Override
public String doOperation() {
return "one";
}
}
4. 测试
@Controller
public class StrategyController {
@Autowired
FactoryForStrategy factoryForStrategy;
@PostMapping("/strategy")
@ResponseBody
public String strategy(@RequestParam("key") String key) {
String result;
try {
result = factoryForStrategy.getStrategy(key).doOperation();
} catch (Exception e) {
result = e.getMessage();
}
return result;
}
}