策略模式
策略模式( Strategy Pattern )又叫也叫政策模式( Policy Pattern) ,它是将定义的算法家族、分别封装起来,让它们之间可以互相替换,从而让算法的变化不会影响到使用算法的用户。属于行为型模式。
原文: Define a family of algor ithms, encapsulate each one, and make them inter changeable.
策略模式的应用场景
策略模式在生活场景中应用也非常多。比如一个人的交税比率与他的工资有关,不同的工资水平对应不同的税率。再比如我们在互联网移动支付的大背景下,每次下单后付款前,需要选择支付方式。

策略模式可以解决在有多种算法相似的情况下,使用if…else 或swith…case所带来的复杂性和臃
肿性。在日常业务开发中,策略模式适用于以下场景:
1、针对同-类型问题,有多种处理方式,每- -种都能独立解决问题;
2、算法需要自由切换的场景;
3、需要屏蔽算法规则的场景。
首先来看下策略模式的通用UML类图:

从UML类图中, 我们可以看到,策略模式主要包含三种角色:
上下文角色( Context) :用来操作策略的上下文环境,屏蔽高层模块(客户端)对策略,算法的直接访问,封装可能存在的变化;
抽象策略角色( Strategy ) : 规定策略或算法的行为;
具体策略角色( ConcreteStrategy ) :具体的策略或算法实现。
注意:策略模式中的上下文环境(Context) ,其职责本来是隔离客户端与策略类的耦合,让客户端完全与上下文环境沟通,无需关系具体策略。
用策略模式实现促销优惠业务场景
课程会有优惠活动,优惠策略会有很多种可能如:领取优惠券抵扣、返现促销、拼团优惠。下面我们用代码来模拟,首先我们创建一个促销策略的抽象
PromotionStrategy :
public interface IPromotionStrategy {
void doPromotion() ;
}
然后分别创建优惠券抵扣策略CouponStrategy类返现促销策略CashbackStrategy类、拼团优惠策略GroupbuyStrategy类和无优惠策略EmptyStrategy类:
CouponStrategy类:
public class CouponStrategy implements IPromotionStrategy {
public void doPromotion() {
System. out. print1n("使用优惠券抵扣");
}
}
CashbackStrategy类:
public class CashbackStrategy implements IPromotionStrategy {
public void doPromotion() {
System. out. print1n("返现,直接打款到支付宝账号");
}
}
GroupbuyStrategy类:
public class GroupbuyStrategy implements IPromotionStrategy {
public void doPromotion() {
System. out. print1n("5人成团,可以优惠");
}
}
EmptyStrategy类:
public class EmptyStrategy implements IPromotionStrategy {
public void doPromotion() {
System. out. print1n("无优惠");
}
}
然后创建促销活动方案PromotionActivity类:
public class PromotionActivity {
private IPromotionStrategy strategy;
public PromotionActivity( IPromotionStrategy strategy) {
this. strategy = strategy;
)
public void execute(){
strategy . doPromotion();
}
}
编写客户端测试类:
public static void main(String[] args) {
PromotionActivity activity618 = new Promoti onActivity(new CouponStrategy());
PromotionActivity activity1111 = new PromotionActivity(new
CashbackStrategy());
activity. execute();
activity. execute();
}
此时,小伙伴们会发现,如果把上面这段测试代码放到实际的业务场景其实并不实用。因为我们做
活动时候往往是要根据不同的需求对促销策略进行动态选择的, 并不会一次性执行多种优惠。 所以,我们的代码通常会这样写:
public static void main(String[] args) {
PromotionActivity promotionActivity = null;
String promotionKey = "COUPON";
if(StringUtils . equals(promoti onKey, "COUPON")){
promotionActivity = new PromotionActivity( new CouponStrategy());
}else if(StringUtils . equals (promotionKey , "CASHBACK")){
promotionActivity = new PromotionActivity(new CashbackStrategy());
}// .... ..
promotionActivity. execute() ;
}
这样改造之后,满足了业务需求,客户可根据自己的需求选择不同的优惠策略了。但是,经过一段时间的业务积累,我们的促销活动会越来越多。于是,我们的程序猿小哥哥就忙不赢了,每次上活动之前都要通宵改代码,而且要做重复测试,判断逻辑可能也变得越来越复杂。这时候,我们是不需要思考代码是不是应该重构了?回顾我们之前学过的设计模式应该如何来优化这段代码呢?其实,我们可以结合单例模式和工厂模式。创建PromotionStrategyFactory类:
public class Promot ionStrategyFacory {
private static Map<String, IPromot ionStrategy> PROMOTIONS = new HashMap<String, IPromot ionStrategy>();
static {
PROMOTIONS. put(PromotionKey . COUPON, new CouponStrategy());
PROMOTIONS. put( PromotionKey . CASHBACK , new CashbackStrategy());
PROMOTIONS. put(PromotionKey. GROUPBUY, new GroupbuyStrategy());
}
private static final IPromotionStrategy EMPTY = new EmptyStrategy();
private Promot ionStrategyFacory(){}
public static IPromot ionStrategy getPromot ionStrategy(String promotionKey){
IPromotionStrategy strategy = PROMOTIONS . get(promotionKey);
return strategy == null ? EMPTY : strategy;
}
private interface PromotionKey{
String COUPON = "COUPON" ;
String CASHBACK = "CASHBACK";
String GROUPBUY = "GROUPBUY" ;
}
public static Set<String> getPromot ionKeys(){
return PROMOTIONS. keySet();
}
代码优化之后,是不是我们程序猿小哥哥的维护工作就轻松了?每次上新活动,不影响原来的代码的逻辑
策略模式在框架源码中的体现
首先来看JDK中一个比较常用的比较器Comparator接口我们看到的一一个大家常用的compare()
方法,就是一个策略抽象实现:
public interface Comparator<T> {
int compare(T 01, T o2);
}
Comparator抽象下面有非常多的实现类我们经常会把Comparator作为参数传入作为排序策略,
例如Arrays类的parallelSort方法等:
public class Arrays{
public static <T> void parallelSort(T[] a, int fromIndex, int toIndex,
Comparator<? super T> cmp) {
...
}
...
}
还有TreeMap的构造方法:
public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, Cloneable, java. io .Serializable{
public TreeMap (Comparator<? super K> comparator) {
this. comparator = comparator ;
}
}
这就是Comparator在JDK源码中的应用。那我们来看策略模式在Spring源码中的应用,来看Resource类:
public interface Resource extends InputStreamSource {
boolean exists();
default boolean isReadable() {
return true;
}
default boolean isOpen() {
return false;
}
default boolean isFile() {
return false;
}
URL getURL() throws IOException;
URI getURI() throws IOException;
File getFile() throws IoException;
default ReadableByteChannel readableChannel() throws IOException {
return Channels . newChannel( this . getInputStream());
}
long contentLength() throws IOException;
long lastModified() throws IOException;
Resource createRelative(String var1) throws IOException;
@Nullable
String getFilename();
String getDescription();
}
我们虽然没有直接使用Resource类,但是我们经常使用它的子类,例如:
还有一个非常典型的场景, Spring的初始化也采用了策略模式,不同的类型的类采用不同的初始化策略。首先有一个InstantiationStrategy接口, 我们来看一下源码 :
public interface InstantiationStrategy {
object instantiate( RootBeanDefinition var1, @Nullable String var2, BeanFactory var3) throws Beans Exception;
Object instantiate( RootBeanDefinition var1, @Nullable String var2, BeanFactory var3, Constructor<?> var4, @Nullable
object... var5) throws BeansException;
object instantiate (RootBeanDefinition var1, @Nullable String var2, BeanFactory var3, @Nu11able object var4, Method
var5, @Nul1able object... var6) throws BeansException;
顶层的策略抽象非常简单,但是它下面有两种策略SimplelnstantiationStrategy和
CglibSubclassingInstantiationStrategy ,我们看一下类图 :
打开类图我们还发现CglibSubclassingInstantiationStrategy 策略类还继承了SimplelnstantiationStrategy类,说明在实际应用中多种策略之间还可以继承使用。小伙们可以作为一个参考,在实际业务场景中,可以根据需要来设计。
策略模式的优缺点
优点:
1、策略模式符合开闭原则。
2、避免使用多重条件转移语句,如if…else…语句,switch 语句
3、使用策略模式可以提高算法的保密性和安全性。
缺点:
1、客户端必须知道所有的策略,并且自行决定使用哪一个策略类。
2、代码中会产生非常多策略类,增加维护难度。