设计模式——策略模式(多种促销优惠方案优化)
很多電商平臺都會推出優(yōu)惠活動。優(yōu)惠策略有很多種,如領(lǐng)取優(yōu)惠券抵扣、返現(xiàn)促銷、拼團優(yōu)惠、秒殺優(yōu)惠等。
下面我們使用策略模式來模擬實現(xiàn)電商中多種促銷優(yōu)惠方案的選擇
首先創(chuàng)建一個抽象策略角色 PromotionStrategy。
/*** @program: PromotionStrategy* @description: 抽象策略角色*/ public interface PromotionStrategy {void doPromotion(); }然后分別創(chuàng)建具體策略 優(yōu)惠券抵扣策略 CouponStrategy 類、返現(xiàn)促銷策略 CashbackStrategy 類、拼團優(yōu)惠策略 GroupBuyStrategy 類和無優(yōu)惠策略 EmptyStrategy 類。
public class CouponStrategy implements PromotionStrategy {public void doPromotion() {System.out.println("使用優(yōu)惠券抵扣");} } public class CashbackStrategy implements PromotionStrategy {public void doPromotion() {System.out.println("返現(xiàn),直接打款到支付寶賬號");} } public class GroupBuyStrategy implements PromotionStrategy {public void doPromotion() {System.out.println("5人成團,可以優(yōu)惠");} } public class EmptyStrategy implements PromotionStrategy {public void doPromotion() {System.out.println("無優(yōu)惠");} }然后創(chuàng)建環(huán)境類
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();} }這樣改造之后,代碼就滿足了業(yè)務(wù)需求,客戶可根據(jù)自己的需求選擇不同的優(yōu)惠策略。但是,經(jīng)過一段時間的業(yè)務(wù)積累,促銷活動會越來越多,程序員就開始經(jīng)常加班,每次上活動之前就要通宵改代碼,而且要做重復(fù)測試,判斷邏輯可能也會變得越來越復(fù)雜。此時,我們就要思考代碼是否需要重構(gòu)。
回顧之前學(xué)過的設(shè)計模式,我們可以結(jié)合單例模式和簡單工廠模式來優(yōu)化這段代碼。創(chuàng)建 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();} }這樣代碼優(yōu)化之后,每次上新活動都不會影響原來的代碼邏輯,程序員的維護工作也變得輕松了。
總結(jié)
以上是生活随笔為你收集整理的设计模式——策略模式(多种促销优惠方案优化)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 网络营销促销的方式有哪些?
- 下一篇: 大话设计模式策略模式_多种方法实现商场促