大話設計模式筆記(二)——商品促銷 策略模式
- 2019 年 10 月 30 日
- 筆記
版權聲明:本文為博主原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。
本文鏈接:https://blog.csdn.net/luo4105/article/details/76542977
第二章商品促銷——策略模式
需求:商品價格計算,並增加折扣條件
工廠模式UML圖
在工廠模式中,調用端代碼會通過折扣工廠類生成折扣對象,折扣對象調用折扣方法。這裡關聯了兩個類,工廠類和抽象折扣類。
策略模式UML圖

在策略模式中,會在策略環境類的構造器中完成折扣類的初始話,並在策略環境的實現方法調用折扣類的折扣算法。這樣調用類只會關聯策略環境類。
簡單工廠模式需要的是生成的對象,所以在客戶端代碼中會存在工廠類和生成類,而策略模式關注的是相應算法,它並不關注算法類對象,所以在客戶端代碼中只會存在context環境類。這樣降低代碼耦合度。
代碼
Context
public class SaleContext { private SaleStrategy saleStrategy = null; public SaleContext(String saleSelector) { switch (saleSelector) { case "打9折": this.saleStrategy = new PercentSaleStrategy(0.9); break; case "打8折": this.saleStrategy = new PercentSaleStrategy(0.8); break; case "滿300減100": this.saleStrategy = new FullSendSaleStrategy(300, 100); break; default: this.saleStrategy = new NormalStrategy(); break; } } public double contextInterface(double money) { return saleStrategy.getSaleMoney(money); } }
SaleStrategy
abstract class SaleStrategy { public abstract double getSaleMoney(double money); }
PercentSaleStrategy(折扣促銷)
class PercentSaleStrategy extends SaleStrategy { private double pecent = 0.0d; public PercentSaleStrategy(double pecent) { this.pecent = pecent; } @Override public double getSaleMoney(double money) { return money * pecent; } }
FullSendSaleStrategy(滿減促銷)
class FullSendSaleStrategy extends SaleStrategy { private double fullMoney = 0.0d; private double sendMonty = 0.0d; public FullSendSaleStrategy(double fullMoney, double sendMonty) { this.fullMoney = fullMoney; this.sendMonty = sendMonty; } @Override public double getSaleMoney(double money) { return money > fullMoney ? (money - sendMonty) : money; } }
總結
策略模式是定義了一系列算法,這些算法從層次上實現相同的功能,最好析取出算法層,可以減少算法之間和調用算法的耦合。
在實際工作中,當聽到需求中包含在不同時間應用不同業務規則,就可以考慮使用策略模式。
設計模式的核心思想就是對接口編程,封裝變化。
應用場景
只要在分析過程中聽到需要在不同時間應用不同的業務規則,就可以考慮使用策略模式。