网站开发和运行 法律,东莞市seo网络推广报价,清远网站建设推广,沈阳的网站制作公司概述
本章我们学习另外一种行为型模式#xff0c;策略模式。在实际开发中#xff0c;这个设计模式也比较常用。最场景的应用场景是#xff0c;利用它来避免冗长的 if-else 或 switch 分支判断。不过#xff0c;它的作用还不止如此。它也可以像模板模式那样#xff0c;提供…概述
本章我们学习另外一种行为型模式策略模式。在实际开发中这个设计模式也比较常用。最场景的应用场景是利用它来避免冗长的 if-else 或 switch 分支判断。不过它的作用还不止如此。它也可以像模板模式那样提供框架的扩展点。 策略模式的原理与实现
策略模式英文全称是 Strategy Design Pattern。在 GoF 的《设计模式》中它是这样定义的 Define a family of algorithms, encapsulate each oneand make them interchangeable. Strategy lets the algorithm vary independently from clients that user it. 中文翻译定义一簇算法类将每个算法分别封装起来让它们可以相互替代。策略模式可以使算法的变化独立于客户端这里的客户端指使用算法的代码。
我们知道工厂模式是解耦对象的创建和使用观察者模式是解耦观察者和被观察者。策略模式跟它们类似也能起到解耦的作用不过它解耦的是策略的定义、创建和使用这三部分。接下来就详细讲讲一个完整的策略模式应该包含的三个部分。
1.策略类的定义
策略类的定义比较简单包含一个策略接口和一组实现接口的策略类。因为所有的策略类都实现相同的接口所以客户端代码基于接口而非实现编程可以灵活地替换不同的策略。代码如下所示
public interface Strategy {void algorithmInterface();
}public class ConcreteStrategyA implements Strategy {Overridepublic void algorithmInterface() {// 具体的算法...}
}public class ConcreteStrategyB implements Strategy {Overridepublic void algorithmInterface() {// 具体的算法...}
}2.策略的创建
因为策略模式会包含一组策略在使用它们的时候一般会通过类型type来判断创建哪个策略来使用。为了封装创建逻辑需要对客户端代码屏蔽创建细节。可以把根据 type 创建策略的逻辑抽离出来放到工厂类中。代码如下所示
public class StrategyFactory {private static final MapString, 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 must not be empty);}return strategies.get(type);}
}一般来讲策略类都是无状态的不包含成员变量只是纯粹的算法这样的策略对象是可以被共享使用的不需要在每次调用 getStrategy() 时都创建一个新的策略对象。针对这种情况可以使用上面的工厂类的实现方式事先创建好每个策略对象缓存到工厂类中用的时候直接返回。
相反如果策略类是有状态的根据业务场景的需要希望每次从工厂方法中获得的都是新创建的策略对象而不是缓存好可共享的策略对象那就需要按照如下方式来实现策略工厂类。
public class StrategyFactory1{public static Strategy getStrategy(String type) {if (type null || type.isEmpty()) {throw new IllegalArgumentException(type must not be empty);}if (type.equals(A)) {return new ConcreteStrategyA();} else if (type.equals(B)) {return new ConcreteStrategyB();}return null;}
}3.策略的使用
刚刚讲了定义和创建现在再看下策略的使用。
策略模式包含一组可选策略客户端代码一般如何确定使用哪个策略呢最常见的是运行时动态确定使用哪种策略这也是策略模式最经典的应用场景。
这里的 “运行时动态” 指的是事先并不知道会使用哪个策略而是在程序运行期间根据配置量、用户输入、计算结果等这些不确定因素动态决定使用哪种策略。接下来通过一个例子来解释下。
// 策略接口EvictionStrategy
// 策略类LruEvictionStrategy、FifoEvictionStrategy、LfuEvictionStrategy...
// 策略工厂EvictionStrategyFactory
public class UserCache {private MapString, 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 properties new Properties();properties.load(new FileInputStream(./config.properties));String type properties.getProperty(eviction_type);evictionStrategy EvictionStrategyFactory.getEvictionStrategy(type);UserCache userCache new UserCache(evictionStrategy);// ...}
}// 非运行时动态确定根据配置文件的配置决定使用哪种策略
public class Application {public static void main(String[] args) throws Exception {// ...EvictionStrategy evictionStrategy new LruEvictionStrategy();UserCache userCache new UserCache(evictionStrategy);// ...}
}从上面的代码可以看出“非运行时动态确定” 也就是第二个 Application 中使用的方式并不能发挥策略模式的优势。在这种应用场景下策略模式实际上退化成了 “面向对象的多态特性” 或 “基于接口而非实现编程原则”。
如何利用策略避免分支判断
实际上能够移除分支判断逻辑的模式不仅仅有策略模式后面要将的状态模式也可以。对于使用哪种模式具体还要看应用场景来决定。策略模式适用于根据不同类型的动态决定使用哪种策略这样一种应用场景。
先通过一个例子来看下if-else 或 switch 分支判断逻辑是如何产生的。具体代码如下所示。在这个例子中我们没有使用策略模式而是将策略的定义、创建、使用直接耦合在一起。
public class OrderService {public double discount(Order order) {double discount 0.0;OrderType orderType order.getOrderType();if (orderType.equals(OrderType.NORMAL)) { // 普通订单// 省略这块计算算法代码...} else if (orderType.equals(OrderType.GROUPON)) { // 团购订单// 省略这块计算算法代码...} else if (orderType.equals(OrderType.PROMOTION)) { // 促销订单// 省略这块计算算法代码...}return discount;}
}如何来移除分支判断逻辑呢策略模式就派上用场了。使用策略模式对上面的代码进行重构将不同类型订单的打折策略设计成策略类并有工厂类来负责创建策略对象。具体代码如下所示
public interface DiscountStrategy {double calcDiscount(Order order);
}public class NormalDiscountStrategy implements DiscountStrategy {Overridepublic double calcDiscount(Order order) {// 省略这块计算算法代码...}
}// 省略GrouponDiscountStrategy、PromotionDiscountStrategy类代码...public class DiscountStrategyFactory {private static final MapOrderType, 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 orderType) {return strategies.get(orderType);}
}public class OrderService {public double discount(Order order) {OrderType orderType order.getOrderType();DiscountStrategy discountStrategy DiscountStrategyFactory.getDiscountStrategy(orderType);return discountStrategy.calcDiscount(order);}
}重构之后的代码就没有 if-else 分支判断语句了。实际上这得益于策略工厂类。在工厂类中我们用 Map 缓存策略根据 type 直接从 Map 中获取对应地策略从而避免 if-else 分支判断逻辑。等后面讲到使用状态模式来避免分支判断逻辑时你会发现它们使用的是同样的套路。本质上都是借助 “查表法”根据 “type” 查表代码中的 strategies 就是表替代根据 type 分支判断。
但是如果业务场景需要每次创建不同的策略对象我们就要用另外一种工厂类的实现方式了。具体代码如下所示
public class DiscountStrategyFactory {public static DiscountStrategy getDiscountStrategy(OrderType orderType) {if (orderType.equals(OrderType.NORMAL)) {return new NormalDiscountStrategy();} else if (orderType.equals(OrderType.GROUPON)) {return new GrouponDiscountStrategy();} else if (orderType.equals(OrderType.PROMOTION)) {return new PromotionDiscountStrategy();}return null;}
}这种实现方式相当于把原来的 if-else 分支逻辑从 OrderService 转移到工厂类中实际上并没有真正将它移除。
总结
策略模式定义一簇算法类将每个算法分别封装起来让它们可以互相替换。策略模式可以使算法的变化独立于使用它们的客户端这里的客户端指使用算法的代码。
策略模式用来解耦策略的定义、创建和使用。实际上一个完整的策略模式就是由这三个部分组成的。
策略类的定义比较简单包含一个策略接口和一组实现这个接口的策略类。策略的创建由工厂类完成封装策略的创建细节。策略模式包含一组策略可选。客户端代码如何选择使用哪个策略有两种确定办法编译时静态确定和运行时动态确定。其中“运行时动态确定” 才是策略模式最典型的应用场景。
此外还可以通过策略模式移除 if-else 分支判断。实际上这得益于工厂类更本质上将是借助 “查表法”根据 type 查表替代根据 type 分支判断。