策略模式的原理与实现

策略模式,英文全称是 Strategy Design Pattern。在 GoF 的《设计模式》一书中,它是这样定义的:

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

翻译成中文就是:定义一组算法类,并将每个算法分别封装起来,让它们可以互相替换,这样在运行时可以灵活的使用其中的一个算法。策略模式可以使算法的变化独立于使用它们的客户端,它的核心思想是在一个计算方法中把容易变化的算法抽出来作为“策略”参数传进去,从而使得新增策略不必修改原有逻辑。

我们知道,工厂模式是解耦对象的创建和使用,观察者模式是解耦观察者和被观察者。策略模式跟两者类似,也能起到解耦的作用,不过,它解耦的是策略的定义、创建、使用这三部分。下面我们详细讲讲一个完整的策略模式应该包含的这三个部分。

1. 策略的定义

策略类的定义比较简单,包含一个策略接口和一组实现这个接口的策略类。因为所有的策略类都实现相同的接口,所以,客户端代码基于接口而非实现编程,可以灵活地替换不同的策略。示例代码如下:

  1. public interface Strategy {
  2. void algorithmInterface();
  3. }
  4. public class ConcreteStrategyA implements Strategy {
  5. @Override
  6. public void algorithmInterface() {
  7. //具体的算法...
  8. }
  9. }
  10. public class ConcreteStrategyB implements Strategy {
  11. @Override
  12. public void algorithmInterface() {
  13. //具体的算法...
  14. }
  15. }

2. 策略的创建

因为策略模式会包含一组策略,在使用它们的时候,一般会通过类型(type)来判断创建哪个策略来使用。为了封装创建逻辑,我们需要对客户端代码屏蔽创建细节。我们可以把根据 type 创建策略的逻辑抽离出来,放到工厂类中。示例代码如下:

  1. public class StrategyFactory {
  2. private static final Map<String, Strategy> strategies = new HashMap<>();
  3. static {
  4. strategies.put("A", new ConcreteStrategyA());
  5. strategies.put("B", new ConcreteStrategyB());
  6. }
  7. public static Strategy getStrategy(String type) {
  8. if (type == null || type.isEmpty()) {
  9. throw new IllegalArgumentException("type should not be empty.");
  10. }
  11. return strategies.get(type);
  12. }
  13. }

一般来讲,如果策略类是无状态的,不包含成员变量,只是纯粹的算法实现,这样的策略对象是可以被共享使用的,不需要在每次调用 getStrategy() 的时候,都创建一个新的策略对象。针对这种情况,我们可以使用上面这种工厂类的实现方式,事先创建好每个策略对象,缓存到工厂类中,用的时候直接返回。相反,如果策略类是有状态的,根据业务场景的需要,那就需要每次返回新创建的策略类。

3. 策略的使用

我们知道,策略模式包含一组可选策略,客户端代码一般如何确定使用哪个策略呢?最常见的是运行时动态确定使用哪种策略,这也是策略模式最典型的应用场景。这里的“运行时动态”指的是,我们事先并不知道会使用哪个策略,而是在程序运行期间,根据配置、用户输入、计算结果等这些不确定因素,动态决定使用哪种策略。接下来,我们通过一个例子来解释一下。

  1. // 策略接口:EvictionStrategy
  2. // 策略类:LruEvictionStrategy、FifoEvictionStrategy、LfuEvictionStrategy...
  3. // 策略工厂:EvictionStrategyFactory
  4. public class UserCache {
  5. private Map<String, User> cacheData = new HashMap<>();
  6. private EvictionStrategy eviction;
  7. public UserCache(EvictionStrategy eviction) {
  8. this.eviction = eviction;
  9. }
  10. //...
  11. }
  12. // 运行时动态确定,根据配置文件的配置决定使用哪种策略
  13. public class Application {
  14. public static void main(String[] args) throws Exception {
  15. Properties props = new Properties();
  16. props.load(new FileInputStream("./config.properties"));
  17. String type = props.getProperty("eviction_type");
  18. EvictionStrategy evictionStrategy = EvictionStrategyFactory.getEvictionStrategy(type);
  19. UserCache userCache = new UserCache(evictionStrategy);
  20. //...
  21. }
  22. }
  23. // 非运行时动态确定,在代码中指定使用哪种策略
  24. public class Application {
  25. public static void main(String[] args) {
  26. EvictionStrategy evictionStrategy = new LruEvictionStrategy();
  27. UserCache userCache = new UserCache(evictionStrategy);
  28. //...
  29. }
  30. }

从上面的代码中可以看到:第二个 Application 中的使用方式,并不能发挥策略模式的优势。在这种应用场景下,策略模式实际上退化成了“面向对象的多态特性”或“基于接口而非实现编程原则”。

如何利用策略模式避免分支判断?

我们先通过一个例子来看下,if-else 或 switch-case 分支判断逻辑是如何产生的。具体的代码如下所示。在这个例子中,我们没有使用策略模式,而是将策略的定义、创建、使用直接耦合在一起。

  1. public class OrderService {
  2. public double discount(Order order) {
  3. double discount = 0.0;
  4. OrderType type = order.getType();
  5. if (type.equals(OrderType.NORMAL)) {
  6. //...普通订单
  7. } else if (type.equals(OrderType.GROUPON)) {
  8. //...团购订单
  9. } else if (type.equals(OrderType.PROMOTION)) {
  10. //...促销订单
  11. }
  12. return discount;
  13. }
  14. }

如何来移除掉分支判断逻辑呢?那策略模式就派上用场了。我们使用策略模式对上面的代码重构,将不同类型订单的打折策略设计成策略类,并由工厂类来负责创建策略对象。具体的代码如下所示:

  1. // 策略的定义
  2. public interface DiscountStrategy {
  3. double calDiscount(Order order);
  4. }
  5. // 策略的创建
  6. public class DiscountStrategyFactory {
  7. private static final Map<OrderType, DiscountStrategy> strategies = new HashMap<>();
  8. static {
  9. strategies.put(OrderType.NORMAL, new NormalDiscountStrategy());
  10. strategies.put(OrderType.GROUPON, new GrouponDiscountStrategy());
  11. strategies.put(OrderType.PROMOTION, new PromotionDiscountStrategy());
  12. }
  13. public static DiscountStrategy getDiscountStrategy(OrderType type) {
  14. return strategies.get(type);
  15. }
  16. }
  17. // 策略的使用
  18. public class OrderService {
  19. public double discount(Order order) {
  20. OrderType type = order.getType();
  21. DiscountStrategy discountStrategy = DiscountStrategyFactory.getDiscountStrategy(type);
  22. return discountStrategy.calDiscount(order);
  23. }
  24. }

重构之后的代码就没有了 if-else 分支判断语句了。实际上,这得益于策略工厂类。在工厂类中,我们用 Map 来缓存策略,根据 type 直接从 Map 中获取对应的策略,从而避免 if-else 分支判断逻辑。但是,即便这样,当我们添加新的策略类时,还是需要修改 DiscountStrategyFactory 的代码,并不完全符合开闭原则。有什么办法让我们完全满足开闭原则呢?

对于 Java 来说,我们可以通过反射来避免对策略工厂类的修改。具体是这么做的:我们通过一个配置文件或自定义的 Annotation 来标注都有哪些策略类;策略工厂类读取配置文件或搜索被 Annotation 标注的策略类,然后通过反射动态地加载这些策略类、创建策略对象;当我们新添加一个策略的时候,只需要将这个新添加的策略类添加到配置文件或者用 Annotation 标注即可。

策略模式使用案例

1. Spring 动态代理实现策略

Spring AOP 支持两种动态代理实现方式,一种是 JDK 提供的动态代理实现方式,另一种是 Cglib 提供的动态代理实现方式。针对不同的被代理类,Spring 会在运行时动态地选择不同的动态代理实现方式。这个应用场景实际上就是策略模式的典型应用场景。

我们前面讲过,策略模式包含策略的定义、创建和使用。在策略模式中,策略的定义这一部分很简单。我们只需要定义一个策略接口,让不同的策略类都实现这一个策略接口。对应到 Spring 源码,AopProxy 就是策略接口,JdkDynamicAopProxy、CglibAopProxy 是两个实现了 AopProxy 接口的策略类。

  1. public interface AopProxy {
  2. Object getProxy();
  3. Object getProxy(ClassLoader var1);
  4. }

在策略模式中,策略的创建一般通过工厂方法来实现。对应到 Spring 源码,AopProxyFactory 是一个工厂类接口,DefaultAopProxyFactory 是一个默认的工厂类,用来创建 AopProxy 对象。

  1. public interface AopProxyFactory {
  2. AopProxy createAopProxy(AdvisedSupport var1) throws AopConfigException;
  3. }
  4. public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
  5. public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
  6. if (!config.isOptimize() && !config.isProxyTargetClass() && !this.hasNoUserSuppliedProxyInterfaces(config)) {
  7. return new JdkDynamicAopProxy(config);
  8. } else {
  9. Class<?> targetClass = config.getTargetClass();
  10. if (targetClass == null) {
  11. throw new AopConfigException("TargetSource cannot determine target class: Either an interface or a target is required for proxy creation.");
  12. } else {
  13. return (AopProxy)(!targetClass.isInterface() && !Proxy.isProxyClass(targetClass) ? new ObjenesisCglibAopProxy(config) : new JdkDynamicAopProxy(config));
  14. }
  15. }
  16. }
  17. //用来判断用哪个动态代理实现方式
  18. private boolean hasNoUserSuppliedProxyInterfaces(AdvisedSupport config) {
  19. Class<?>[] ifcs = config.getProxiedInterfaces();
  20. return ifcs.length == 0 || ifcs.length == 1 && SpringProxy.class.isAssignableFrom(ifcs[0]);
  21. }
  22. }

策略模式的典型应用场景,一般是通过环境变量、状态值、计算结果等动态地决定使用哪个策略。对应到 Spring 源码中,我们可以参看 DefaultAopProxyFactory 类中的 createAopProxy() 函数的代码实现。其中,第 8 行代码就是动态选择哪种策略的判断条件。