一、策略模式定义

1.策略模式又称政策模式,它是将定义的算法家族、分别封装起来,让它们之间可以互相替换,从而让算法的变化不会影响到使用算法的用户,属于行为型模式

2.策略模式使用的就是面向对象的继承和多态机制,从而实现同一行为在不同场景下具备不同实现

3.策略模式的应用场景:

  A.针对同一类型问题,有多种处理方式,每一种都能独立解决问题

  B.算法需要自由切换的场景

  C.需要屏蔽算法规则的场景

二、策略模式示例

1.策略模式主要包含三种角色:

  A.上下文角色(Context):用来操作策略的上下文环境,屏蔽高层模块(客户端)对策略、算法的直接访问,封装可能存在的变化

  B.抽象策略角色(Strategy):规定策略或算法的行为

  C.具体策略角色(ConcreteStrategy):具体的策略或算法实现

2.代码示例

 1 public interface IPromotionStrategy {
 2     void doPromotion();
 3 }
 4 
 5 public class CouponStrategy implements IPromotionStrategy {
 6     @Override
 7     public void doPromotion() {
 8         System.out.println("使用优惠券抵扣");
 9     }
10 }
11 
12 public class GroupbuyStrategy implements IPromotionStrategy {
13     @Override
14     public void doPromotion() {
15         System.out.println("5人成团,可以优惠");
16     }
17 }
18 
19 public class PromotionActivity {
20 
21     private IPromotionStrategy strategy;
22 
23     public PromotionActivity(IPromotionStrategy strategy){
24         this.strategy = strategy;
25     }
26 
27     public void execute(){
28         strategy.doPromotion();
29     }
30 }
31 
32 public class StrategyTest {
33 
34     public static void main(String[] args) {
35         PromotionActivity activity = new PromotionActivity(new CouponStrategy());
36         activity.execute();
37     }
38 }

3.策略模式的优缺点

  A.优点

    a.策略模式符合开闭原则

    b.避免使用多重条件转移语句,如if...else...语句、switch语句

    c.使用策略模式可以提高算法的保密性和安全性

  B.缺点

    a.客户端必须知道所有的策略,并且自行决定使用哪一个策略类

    b.代码中会产生非常多的策略类,增加维护难度