策略模式,英文全称是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.
翻译成中文就是:定义一族算法类,将每个算法分别封装起来,让它们可以互相替换。策略模式可以使算法的变化独立于使用它们的客户端(这里的客户端代指使用算法的代码)。我们知道,工厂模式是解耦对象的创建和使用,观察者模式是解耦观察者和被观察者。策略模式跟两者类似,也能起到解耦的作用,不过,它解耦的是策略的定义、创建、使用这三部分。接下来,我就详细讲讲一个完整的策略模式应该包含的这三个部分。
![](https://img-blog.csdnimg.cn/20201126141704170.png)
策略的定义
策略类的定义比较简单,包含一个策略接口和一组实现这个接口的策略类。因为所有的策略类都实现相同的接口,所以,客户端代码基于接口而非实现编程,可以灵活地替换不同的策略。示例代码如下所示:
public interface EvictionStrategy {
void evictAlgorithmI();
}
public class LruEvictionStrategy implements Strategy {
@Override
public void evictAlgorithmI() {
//具体的算法
}
}
public class FifoEvictionStrategy implements Strategy {
@Override
public void evictAlgorithmI() {
//具体的算法
}
}
策略的创建
因为策略模式会包含一组策略,在使用它们的时候,一般会通过类型(type)来判断要创建哪个策略。为了封装创建逻辑,我们需要对客户端代码屏蔽创建细节。我们可以把根据 type创建策略的逻辑抽离出来,放到工厂类中。示例代码如下所示:
public class EvictionStrategyFactory {
private static final Map<String, Strategy> container = new HashMap();
static {
container.put("LRU", new LruEvictionStrategy());
container.put("FIFO", new FifoEvictionStrategy());
}
public static EvictionStrategy getStatelessEvictionStrategy(String type) {
if (StringUtils.isBlank(type) {
throw new IllegalArgumentException("type should not be blank.");
}
return container.get(type.toUpperCase());
}
public static EvictionStrategy getStatefulEvictionStrategy(String type) {
if (StringUtils.isBlank(type) {
throw new IllegalArgumentException("type should not be blank.");
}
if ("LRU".equals(type.toUpperCase())) {
return new LruEvictionStrategy();
} else if ("FIFO".equals(type.toUpperCase())) {
return new FifoEvictionStrategy();
}
return null;
}
}
一般来讲,如果策略类是无状态的,不包含成员变量,只是纯粹的算法实现,这样的策略对象是可以被共享使用的,不需要在每次获取策略的时候,都创建一个新的策略对象。针对这种情况,我们可以使用上面getStatelessEvictionStrategy()这个方法,事先创建好每个策略对象,缓存到工厂类中,用的时候直接返回,这里本质上是一种“查表法”,即根据type查表代替根据type作分支判断。相反,如果策略类是有状态的,根据业务场景的需要,我们希望每次从工厂方法中,获得的都是新创建的策略对象,而不是缓存好可共享的策略对象,那我们可以使用getStatefulEvictionStrategy()方法来获取策略对象。
策略的使用
上面说了策略的定义和创建,现在,我们再来看一下,策略的使用。我们知道,策略模式包含一组可选策略,客户端代码一般如何确定使用哪个策略呢?最常见的是运行时动态确定使用哪种策略,这也是策略模式最典型的应用场景。这里的“运行时动态”指的是,我们事先并不知道会使用哪个策略,而是在程序运行期间,根据配置、用户输入、计算结果等这些不确定因素,动态决定使用哪种策略。示例如下:
public class Application {
public static void main(String[] args) throws Exception {
//非运行时动态确定,在代码中指定使用哪种策略
EvictionStrategy evictionStrategy = new LruEvictionStrategy();
UserCache userCache1 = new UserCache(evictionStrategy);
//...
//运行时动态确定,根据配置文件的配置决定使用哪种策略
evictionStrategy = null;
Properties props = new Properties();
props.load(new FileInputStream("./eviction_config.properties"));
String type = props.getProperty("eviction_type");
evictionStrategy = EvictionStrategyFactory.getStatelessEvictionStrategy(type.toUpperCase());
UserCache userCache2 = new UserCache(evictionStrategy);
//...
}
}
从上面代码可以看出,非运行时动态确定并不能发挥策略模式的优势。在这种应用场景下,策略模式实际上退化成了"面向对象的多态特性"或"基于接口而非实现编程原则"。
总结
策略模式用来解耦策略的定义、创建、使用。一个完整的策略模式就是由这三个部分组成的。
- 策略类的定义比较简单,包含一个策略接口和一组实现这个接口的策略类。
- 策略的创建由工厂类来完成,封装策略创建的细节。
- 策略模式包含一组策略可选,客户端代码如何选择使用哪个策略,有两种确定方法:编译时静态确定和运行时动态确定。其中,“运行时动态确定”才是策略模式最典型的应用场景。