策略模式的原理与实现

定义一族算法类,将每个算法分别封装起来,让它们可以互相替换。策略模式可以使算法的变化独立于使用它们的客户端(这里的客户端代指使用算法的代码)。

它解耦的是策略的定义、创建、使用这三部分。

策略的定义

  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. }

策略的创建

利用工厂模式:

  1. // 无状态对象, 提前创建
  2. public class StrategyFactory {
  3. private static final Map<String, Strategy> strategies = new HashMap<>();
  4. static {
  5. strategies.put("A", new ConcreteStrategyA());
  6. strategies.put("B", new ConcreteStrategyB());
  7. }
  8. public static Strategy getStrategy(String type) {
  9. if (type == null || type.isEmpty()) {
  10. throw new IllegalArgumentException("type should not be empty.");
  11. }
  12. return strategies.get(type);
  13. }
  14. }
  15. // 有状态
  16. public class StrategyFactory {
  17. public static Strategy getStrategy(String type) {
  18. if (type == null || type.isEmpty()) {
  19. throw new IllegalArgumentException("type should not be empty.");
  20. }
  21. if (type.equals("A")) {
  22. return new ConcreteStrategyA();
  23. } else if (type.equals("B")) {
  24. return new ConcreteStrategyB();
  25. }
  26. return null;
  27. }
  28. }

策略的使用

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

实际上,这得益于策略工厂类。我们用 Map 来缓存策略,根据 type 直接从 Map 中获取对应的策略,从而避免 if-else 分支判断逻辑。本质上都是借助“查表法”,根据 type 查表(代码中的 strategies 就是表)替代根据 type 分支判断。

总结

策略模式就是对同一个接口有不同实现, 这些实现在不同条件下都有机会使用.