1. 程式人生 > 實用技巧 >學習筆記-設計模式之策略模式

學習筆記-設計模式之策略模式

本文內容源於視訊教程,若有侵權,請聯絡作者刪除。

一、概念

策略模式(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 }