定义

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

策略模式定义了一系列算法,并将每个算法封装起来,使它们可以相互替换,且算法的变化不会影响使用算法的客户。策略模式属于对象行为模式,它通过对算法进行封装,把使用算法的责任和算法的实现分割开来,并委派给不同的对象对这些算法进行管理。

结构

主要角色:

  1. 抽象策略(Strategy)类:定义了一个公共接口,各种不同的算法以不同的方式实现这个接口,环境角色使用这个接口调用不同的算法,一般使用接口或抽象类实现。
  2. 具体策略(Concrete Strategy)类:实现了抽象策略定义的接口,提供具体的算法实现。
  3. 环境(Context)类:持有一个策略类的引用,最终给客户端调用。

结构图:
image.png
**

应用

基本用法

传统的可以使用工厂模式进行策略选择,实际开发一般利用spring的注入和注解进行策略选择

  1. public interface DiscountStrategy {
  2. boolean match(String type);
  3. double calDiscount(Order order);
  4. }
  5. @Component
  6. public class NormalDiscountStrategy implements DiscountStrategy {
  7. ...
  8. }
  9. @Component
  10. public class GrouponDiscountStrategy implements DiscountStrategy {
  11. ...
  12. }
  13. @Component
  14. public class PromotionDiscountStrategy implements DiscountStrategy {
  15. ...
  16. }
  17. @Service
  18. public class OrderService {
  19. @Autowired
  20. List<DiscountStrategy> discountStrategyList;
  21. public double discount(Order order) {
  22. String type = order.getType();
  23. for (DiscountStrategy strategy: discountStrategyList) { // 除了简单的循环匹配,根据实际情况可考虑性能更快的策略匹配方法
  24. if (strategy.match(type)) {
  25. return strategy.calDiscount(order)
  26. }
  27. }
  28. throw new Exception('no supported strategy for order type' + type);
  29. }
  30. }


优点

  1. 多重条件语句不易维护,而使用策略模式可以避免使用多重条件语句,如 if…else 语句、switch…case 语句。
  2. 策略模式提供了一系列的可供重用的算法族,恰当使用继承可以把算法族的公共代码转移到父类里面,从而避免重复的代码。
  3. 策略模式可以提供相同行为的不同实现,客户可以根据不同时间或空间要求选择不同的。
  4. 策略模式提供了对开闭原则的完美支持,可以在不修改原代码的情况下,灵活增加新算法。
  5. 策略模式把算法的使用放到环境类中,而算法的实现移到具体策略类中,实现了二者的分离。

缺点

  1. 客户端必须理解所有策略算法的区别,以便适时选择恰当的算法类。
  2. 策略模式造成很多的策略类,增加维护难度。