⚪策略模式
Strategy Design Pattern
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
定义了一个算法族,将每个算法分别封装起来,使得它们之间可以相互替换
让算法的变化独立于使用它的客户。
策略模式解耦的是策略的定义、创建、使用。
策略的定义:包含一个策略接口和一组实现该接口的策略类(基于接口编程,方便运行时切换)
策略的创建:由工厂类完成,封装策略创建的细节
策略模式包含一组可选策略,选择使用哪个策略,有两种方法:
编译时静态确定
运行时动态确定:最典型的应用场景
eg1. 静态确定
// 注意:并不能发挥策略模式的优势,此时策略模式实际上退化成了“面向对象的多态特性”或“基于接口而非实现编程原则”
EvictionStrategy evictionStrategy = new LruEvictionStrategy()
UserCache userCache = new UserCache(evictionStrategy)
eg2. 动态确定
// 根据 type,用工厂创建
EvictionStrategy evictionStrategy = EvictionStrategyFactory.getEvictionStrategy(type)
UserCache userCache = new UserCache(evictionStrategy)
OrderType type = order.getType()
DiscountStrategy discountStrategy = DiscountStrategyFactory.getDiscountStrategy(type)
discountStrategy.calDiscount(order)

设计原则
策略模式
封装变化
变化的是:策略的定义,比如算法的内部实现、算法的数目
针对接口编程
一组策略类实现了相同的策略接口
优先使用组合
客户 has-a 策略接口
松耦合
策略的定义 vs 策略的使用
Last updated