22. Strategy
關於 Strategy 本篇將討論以下幾個問題
1. 關於 Strategy
2. UML
3. 將 UML 轉為程式碼
4. 情境
測試環境:
OS:Windows 10
IDE:Visual Studio 2019
1. 關於 Strategy
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
by Gang of Four
- 定義並封裝一系列演算法,並使它們可切換
- 策略模式使演算法可依據呼叫端指定而抽換
Strategy(策略)屬於行為型(Behavioral Patterns),當遇到一段程式其中有部分邏輯可由外部指定 時,可藉由 Strategy 將邏輯拆分成獨立 class,之後新增邏輯時只需新增 Strategy 實作即可。
優點:
- 符合 開閉原則(Open Closed Principle)
缺點:
2. UML
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
Class 間關聯:
- Context 可包含 Strategy
- ConcreteStrategy A/B/C 繼承 Strategy
Class:
- Context:使用演算法的物件
- Strategy:策略的抽象類別或介面
- ConcreteStrategy:策略實作
3. 將 UML 轉為程式碼
策略介面
策略實作 A
策略實作 B
策略實作 C
使用演算法的物件
- 建立
context
並指定策略實作 A / B / C
- 呼叫策略實作 A / B / C
執行結果
4. 情境
我們接到了一個使用者在線上商城可自行選擇折扣方案的需求
策略介面
策略實作,拆分各種計算結帳金額邏輯
依據使用者選擇折扣計算結帳金額
- 建立
context
並選定折扣
- 輸入結帳金額計算折扣
執行結果
完整程式碼
GitHub:Behavioral_09_Strategy
總結
在初期策略數量少且不知道未來會不會增加時使用 Strategy 會提高程式複雜度,建議直接使用 Delegates 來傳入,等到策略數量增加時再使用 Strategy 重構即可。
參考資料
- Design Patterns
- 大話設計模式
- dofactory
- Refactoring.Guru
新手上路,若有錯誤還請告知,謝謝