策略模式,最常见的应用场景是,利用它来避免冗长的 if-else 或 switch 分支判断,它也可以像模板模式那样,提供框架的扩展点等等。
策略模式的原理与实现
定义一族算法类,将每个算法分别封装起来,让它们可以互相替换。策略 模式可以使算法的变化独立于使用它们的客户端(这里的客户端代指使用算法的代码)。
工厂模式是解耦对象的创建和使用,观察者模式是解耦观察者和被观察者,策略模式跟两者类似,也能起到解耦的作用,不过,它解耦的是策略的定义、创建、使用这三部分。
1. 策略的定义
策略类的定义比较简单,包含一个策略接口和一组实现这个接口的策略类。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public interface Strategy { void algorithmInterface(); } public class ConcreteStrategyA implements Strategy { @Override public void algorithmInterface() { } } public class ConcreteStrategyB implements Strategy { @Override public void algorithmInterface() { } }
|
2. 策略的创建
因为策略模式会包含一组策略,在使用它们的时候,一般会通过类型(type)来判断创建哪个策略来使用。为了封装创建逻辑,需要对客户端代码屏蔽创建细节。可以把根据 type 创建策略的逻辑抽离出来,放到工厂类中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public class StrategyFactory { private static final Map<String, Strategy> strategies = new HashMap<>(); static { strategies.put("A", new ConcreteStrategyA()); strategies.put("B", new ConcreteStrategyB()); } public static Strategy getStrategy(String type) { if (type == null || type.isEmpty()) { throw new IllegalArgumentException("type should not be empty."); } return strategies.get(type); } }
|
如果策略类是无状态的,只包含算法实现,可以被共享,就可以使用上面这种方法实现。
但是如果策略类是有状态的,需要根据业务场景的需要获得不同的对象,那么就需要如下方式创建:
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class StrategyFactory { public static Strategy getStrategy(String type) { if (type == null || type.isEmpty()) { 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; } }
|
3. 策略的使用
策略模式包含一组可选策略,客户端代码一般是运行时动态确定使用哪种策略,这也是策略模式最典型的应用场景。
这里的“运行时动态”指的是,我们事先并不知道会使用哪个策略,而是在程序运行期间, 根据配置、用户输入、计算结果等这些不确定因素,动态决定使用哪种策略。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
public class UserCache { private Map<String, User> cacheData = new HashMap<>(); private EvictionStrategy eviction; public UserCache(EvictionStrategy eviction) { this.eviction = eviction; } }
public class Application { public static void main(String[] args) throws Exception { EvictionStrategy evictionStrategy = null; Properties props = new Properties(); props.load(new FileInputStream("./config.properties")); String type = props.getProperty("eviction_type"); evictionStrategy = EvictionStrategyFactory.getEvictionStrategy(type); UserCache userCache = new UserCache(evictionStrategy); } }
public class Application { public static void main(String[] args) { EvictionStrategy evictionStrategy = new LruEvictionStrategy(); UserCache userCache = new UserCache(evictionStrategy); } }
|
使用策略模式来避免分支
分支代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class OrderService { public double discount(Order order) { double discount = 0.0; OrderType type = order.getType(); if (type.equals(OrderType.NORMAL)) { } else if (type.equals(OrderType.GROUPON)) { } else if (type.equals(OrderType.PROMOTION)) { } return discount; } }
|
使用策略模式代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| public interface DiscountStrategy { double calDiscount(Order order); }
public class DiscountStrategyFactory { private static final Map<OrderType, DiscountStrategy> strategies = new HashMap<>(); static { strategies.put(OrderType.NORMAL, new NormalDiscountStrategy()); strategies.put(OrderType.GROUPON, new GrouponDiscountStrategy()); strategies.put(OrderType.PROMOTION, new PromotionDiscountStrategy()); } public static DiscountStrategy getDiscountStrategy(OrderType type) { return strategies.get(type); } }
public class OrderService { public double discount(Order order) { OrderType type = order.getType(); DiscountStrategy discountStrategy = DiscountStrategyFactory.getDiscountStrategy(); return discountStrategy.calDiscount(order); } }
|
这里通过提前在map冲存储相应的类型,直接从map中获取,而不再用那些if判断。
参考
《设计模式之美》