设计模式——策略模式(多种促销优惠方案优化)
生活随笔
收集整理的這篇文章主要介紹了
设计模式——策略模式(多种促销优惠方案优化)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
很多電商平臺都會推出優惠活動。優惠策略有很多種,如領取優惠券抵扣、返現促銷、拼團優惠、秒殺優惠等。
下面我們使用策略模式來模擬實現電商中多種促銷優惠方案的選擇
首先創建一個抽象策略角色 PromotionStrategy。
/*** @program: PromotionStrategy* @description: 抽象策略角色*/ public interface PromotionStrategy {void doPromotion(); }然后分別創建具體策略 優惠券抵扣策略 CouponStrategy 類、返現促銷策略 CashbackStrategy 類、拼團優惠策略 GroupBuyStrategy 類和無優惠策略 EmptyStrategy 類。
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 strategy;public PromotionActivity(PromotionStrategy strategy) {this.strategy = strategy;}public void execute() {strategy.doPromotion();} } public class Test {public static void main(String[] args) {PromotionActivity activity = null;String promotionKey = "COUPON";if (StringUtils.equals(promotionKey, "COUPON")) {activity = new PromotionActivity(new CouponStrategy());} else if (StringUtils.equals(promotionKey, "CASHBACK")) {activity = new PromotionActivity(new CashbackStrategy());}activity.execute();} }這樣改造之后,代碼就滿足了業務需求,客戶可根據自己的需求選擇不同的優惠策略。但是,經過一段時間的業務積累,促銷活動會越來越多,程序員就開始經常加班,每次上活動之前就要通宵改代碼,而且要做重復測試,判斷邏輯可能也會變得越來越復雜。此時,我們就要思考代碼是否需要重構。
回顧之前學過的設計模式,我們可以結合單例模式和簡單工廠模式來優化這段代碼。創建 PromotionStrategyFactory 類。
private static Map<String, PromotionStrategy> PROMOTIONS = new HashMap<String, PromotionStrategy>();static {PROMOTIONS.put(PromotionKey.COUPON, new CouponStrategy());PROMOTIONS.put(PromotionKey.CASHBACK, new CashbackStrategy());PROMOTIONS.put(PromotionKey.GROUPBUY, new GroupBuyStrategy());}private static final PromotionStrategy EMPTY = new EmptyStrategy();private PromotionStrategyFactory() {}public static PromotionStrategy getPromotionStrategy(String promotionKey) {PromotionStrategy strategy = PROMOTIONS.get(promotionKey);return strategy == null ? EMPTY : strategy;}private interface PromotionKey {String COUPON = "COUPON";String CASHBACK = "CASHBACK";String GROUPBUY = "GROUPBUY";}}這時客戶端測試代碼如下。
public class Test {public static void main(String[] args) {PromotionStrategyFactory.getPromotionKeys();String promotionKey = "COUPON";PromotionStrategy promotionStrategy = PromotionStrategyFactory.getPromotionStrategy(promotionKey);promotionStrategy.doPromotion();} }這樣代碼優化之后,每次上新活動都不會影響原來的代碼邏輯,程序員的維護工作也變得輕松了。
總結
以上是生活随笔為你收集整理的设计模式——策略模式(多种促销优惠方案优化)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网络营销促销的方式有哪些?
- 下一篇: 大话设计模式策略模式_多种方法实现商场促