设计模式之——策略模式

2019-10-19  本文已影响0人  vincent浩哥

策略模式(Strategy Pattern)是指定义了算法家族、分别封装起来,让它们之间可以互相替换,此模式让算法的变化不会影响到使用算法的用户。

应用场景
1.代码中有多个类,他们的区别是行为不同,可以用策略模式
2.一个系统需要动态地在几种算法中选择一种,需要知道所有的算法

经典的业务场景:支付方式

代码演示

//促销策略抽象接口
public interface PromotionStrategy {
    void doPromotion();
}

//优惠券实现
public class CouponStrategy implements PromotionStrategy {
    public void doPromotion() {
        System.out.println("领取优惠券,课程的价格直接减优惠券面值抵扣");
    }
}

//返现活动
public class CashbackStrategy implements PromotionStrategy {
    public void doPromotion() {
        System.out.println("返现促销,返回的金额转到支付宝账号");
    }
}

//团购优惠
public class GroupbuyStrategy implements PromotionStrategy{
    public void doPromotion() {
        System.out.println("拼团,满5人成团,全团享受团购价");
    }
}

// 无优惠
public class EmptyStrategy implements PromotionStrategy {
    public void doPromotion() {
        System.out.println("无促销活动");
    }
}

/**
* 优惠活动
*/
public class PromotionActivity {
    private PromotionStrategy promotionStrategy;
    //构造方法传入策略类型
    public PromotionActivity(PromotionStrategy promotionStrategy) {
        this.promotionStrategy = promotionStrategy;
    }
    //执行策略
    public void execute(){
        promotionStrategy.doPromotion();
    }
}

//testing
public static void main(String[] args) {
    PromotionActivity activity618 = new PromotionActivity(new     CouponStrategy());
    PromotionActivity activity1111 = new PromotionActivity(new     CashbackStrategy());
    activity618.execute();
    activity1111.execute();
}

//利用工厂模式和单例模式改造
/**
* 促销策略工厂
*/
public class PromotionStrategyFactory {
    private static Map<String,PromotionStrategy> PROMOTION_STRATEGY_MAP = new HashMap<String,
PromotionStrategy>();
    static {
        PROMOTION_STRATEGY_MAP.put(PromotionKey.COUPON,new CouponStrategy());
        PROMOTION_STRATEGY_MAP.put(PromotionKey.CASHBACK,new CashbackStrategy());
        PROMOTION_STRATEGY_MAP.put(PromotionKey.GROUPBUY,new GroupbuyStrategy());
    }

    private static final PromotionStrategy NON_PROMOTION = new EmptyStrategy();

    private PromotionStrategyFactory(){}

    public static PromotionStrategy getPromotionStrategy(String promotionKey){
        PromotionStrategy promotionStrategy = PROMOTION_STRATEGY_MAP.get(promotionKey);
        return promotionStrategy == null ? NON_PROMOTION : promotionStrategy;
}
    private interface PromotionKey{
        String COUPON = "COUPON";
        String CASHBACK = "CASHBACK";
        String GROUPBUY = "GROUPBUY";
    }
}

//testing
public static void main(String[] args) {
    String promotionKey = "GROUPBUY";
    PromotionActivity promotionActivity = new PromotionActivity(PromotionStrategyFactory.getPromotionStrategy(promotionKey));
    promotionActivity.execute();
}

优点

1、策略模式符合开闭原则。
2、避免使用多重条件转移语句,如 if...else...语句、switch 语句
3、使用策略模式可以提高算法的保密性和安全性

缺点

1、客户端必须知道所有的策略,并且自行决定使用哪一个策略类。
2、代码中会产生非常多策略类,增加维护难度。

上一篇下一篇

猜你喜欢

热点阅读