学习笔记-设计模式之策略模式
本文内容源于视频教程,若有侵权,请联系作者删除。
一、概念
策略模式(Strategy Pattern)是指定义了算法家族、分别封装起来,让它们之间可以互相替换,此模式让算法的变化不会影响到使用算法的用户。
简言之:为达到某种目的有多个方案,策略模式就是将这些方案封装起来,以便使用。
二、实现
需求:实现促销活动(无促销,限时,优惠券),用户可以任意选择一种优惠策略。
创建促销活动抽象类,并持有开启活动方法。
1 /** 2 * 活动策略 3 */ 4 public interface PromotionStrategy { 5 6 /** 7 * 执行活动 8 */ 9 void execute(); 10 }
创建无促销,限时,优惠券活动并实现活动抽象类
1 public class CouponPromotion implements PromotionStrategy { 2 @Override 3 public void execute() { 4 System.out.println("优惠券活动"); 5 } 6 }
1 public class DiscountPromotion implements PromotionStrategy { 2 @Override 3 public void execute() { 4 System.out.println("限时折扣活动"); 5 } 6 }
1 public class EmptyPromotion implements PromotionStrategy { 2 @Override 3 public void execute() { 4 System.out.println("无促销活动"); 5 } 6 }
编写测试类
1 public class PromotionStrategyTest { 2 3 public static void main(String[] args) { 4 String promotionKey = "COUPON"; 5 PromotionStrategy promotionStrategy = getPromotionStrategy(promotionKey); 6 promotionStrategy.execute(); 7 } 8 9 private static PromotionStrategy getPromotionStrategy(String promotionKey){ 10 PromotionStrategy promotionStrategy; 11 if ("COUPON".equals(promotionKey)){ 12 promotionStrategy = new CouponPromotion(); 13 } else if ("DISCOUNT".equals(promotionKey)){ 14 promotionStrategy = new DiscountPromotion(); 15 } else { 16 promotionStrategy = new EmptyPromotion(); 17 } 18 return promotionStrategy; 19 } 20 }
执行结果:
优惠券活动
由此可见,策略模式是把限时,优惠券活动封装起来,由调用方决定使用哪一种活动。
然而,当活动增加时,每个调用方要新增else if判断,违背了开闭原则,下面通过单例+工厂去掉if else判断。
新增工厂类
1 public class PromotionStrategyFactory { 2 3 private static Map<String, PromotionStrategy> promotionMap = new HashMap<>(); 4 5 static { 6 promotionMap.put("COUPON", new CouponPromotion()); 7 promotionMap.put("DISCOUNT", new DiscountPromotion()); 8 } 9 10 private PromotionStrategyFactory() { 11 } 12 13 public static PromotionStrategy getInstance(String promotionKey){ 14 PromotionStrategy promotionStrategy = promotionMap.get(promotionKey); 15 if (null == promotionStrategy){ 16 promotionStrategy = new EmptyPromotion(); 17 } 18 return promotionStrategy; 19 } 20 21 }
测试类
1 public class PromotionStrategyTest { 2 3 public static void main(String[] args) { 4 String promotionKey = "coupon"; 5 PromotionStrategy activity = PromotionStrategyFactory.getInstance(promotionKey); 6 activity.execute(); 7 } 8 9 }