BetterY00 2019-11-17
定义:定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化不会影响到使用算法的用户。
类型:行为型
适用场景:
优点:
缺点:
某知识平台的教学视频促销(满减、立减、返现)
促销策略接口
public interface PromotionStrategy { void doPromotion(); }
返现策略
public class FanXianPromotionStrategy implements PromotionStrategy{ @Override public void doPromotion() { System.out.println("返现促销,返回的金额存放到慕课网用户的余额中"); } }
立减策略
public class LiJianPromotionStrategy implements PromotionStrategy { @Override public void doPromotion() { System.out.println("立减促销,课程的价格直接减去配置的价格"); } }
满减策略
public class ManJianPromotionStrategy implements PromotionStrategy{ @Override public void doPromotion() { System.out.println("满减促销,满200-20元"); } }
促销活动
public class PromotionActivity { private PromotionStrategy promotionStrategy; public PromotionActivity(PromotionStrategy promotionStrategy) { this.promotionStrategy = promotionStrategy; } public void executePromotionStrategy(){ promotionStrategy.doPromotion(); } }
public class Test { public static void main(String[] args) { PromotionActivity promotionActivity618 = new PromotionActivity(new LiJianPromotionStrategy()); PromotionActivity promotionActivity1111 = new PromotionActivity(new FanXianPromotionStrategy()); promotionActivity618.executePromotionStrategy(); promotionActivity1111.executePromotionStrategy(); } }
结果: