- 策略的定义
- 策略的创建
- 策略的使用
- 策略模式和模板模式的区别
策略模式最常见的应用场景是,用来避免冗长的if-else或switch分支判断。也可以像模板模式那样,提供框架的扩展点等等。
工厂模式是解耦对象的创建和使用,观察者模式是解耦观察者和被观察者。策略模式跟两者类似,也能起到解耦的作用,不过,它解耦的是策略的定义、创建、使用这三部分。
策略的定义策略的定义包括一个策略接口和一系列实现了这个接口的策略类,客户端调用不同策略时可以面向接口编程,灵活替换不同的策略。
//统一的策略接口
public interface Strategy {
void algorithmInterface();
}
public class ConcreteStrategyA implements Strategy {
@Override
public void algorithmInterface() {
//具体的算法A...
}
}
public class ConcreteStrategyB implements Strategy {
@Override
public void algorithmInterface() {
//具体的算法B...
}
}
策略的创建
为了封装创建逻辑,我们需要对客户端代码屏蔽创建细节。我们可以把根据type创建策略的逻辑抽离出来,放到工厂类中。
public class StrategyFactory {
public static final Map strategies = new HashMap<>();
static {
strategies.put("A",new ConcreteStrategyA());
strategies.put("B",new ConcreteStrategyB());
}
public static Strategy getStrategy(Strategy type) {
if (type == null) {
throw new IllegalArgumentException("type should not be empty.");
}
return strategies.get(type);
}
}
这里的策略工厂,用Map来缓存策略,根据type直接从Map中获取对应的策略,从而避免if-else分支判断逻辑。本质上是借助“查表法”,根据type查表(代码中的strategies就是表)替代根据type分支判断。
一般来讲,如果策略类是无状态的,不包含成员变量,只是纯粹的算法实现,这样的策略对象是可以被共享使用的,不需要在每次调用getStrategy()的时候,都创建一个新的策略对象。针对这种情况,我们可以使用上面这种工厂类的实现方式,事先创建好每种策略对象,缓存到工厂类中,用的时候直接返回。
相反,如果策略类是有状态的,根据业务场景的需要,我们希望每次从工厂方法中,获得的都得是新创建的策略对象,而不是缓存好可共享的策略对象,那我们就需要按照如下方式来实现策略工厂类。public static Strategy getStrategy(String type) { if (type == null) { throw new IllegalArgumentException("type should not be empty."); } if (type.equals("A")) { return new ConcreteStrategyA(); } else if (type.equals("B")) { return new ConcreteStrategyB(); } return null; } } ```
策略的使用这种实现方式相当于把原来的if-else分支逻辑,从原来的类中转移到了工厂类中,实际上并没有真正将它移除。
解决方式:
策略模式包含一组可选策略,客户端代码一般如何确定使用哪个策略呢?最常见的是运行时动态确定使用哪种策略,这也是策略模式最典型的应用场景。这里的“运行时动态”指的是,我们事先并不知道会使用哪个策略,而是在程序运行期间,根据配置、用户输入、计算结果等这些不确定因素,动态决定使用哪种策略。
// 运行时动态确定,根据配置文件的配置决定使用哪种策略
public class Application {
public static void main(String[] args) throws Exception {
Strategy strategy = null;
Properties props = new Properties();
props.load(new FileInputStream("./config.properties"));
String type = props.getProperty("eviction_type");
strategy = StrategyFactory.getStrategy(type);
//...
}
}
// 非运行时动态确定,在代码中指定使用哪种策略
public class Application {
public static void main(String[] args) {
//...
Strategy strategy = new ConcreteStrategyA();
//...
}
}
“非运行时动态确定”,也就是第二个Application中的使用方式,并不能发挥策略模式的优势。在这种应用场景下,策略模式实际上退化成了“面向对象的多态特性”或“基于接口而非实现编程原则”。
策略模式和模板模式的区别参考链接:
https://blog.csdn.net/happyever2012/article/details/45844493?spm=1001.2014.3001.5501
https://blog.csdn.net/laokerr/article/details/85619407#comments_15250531



