每天一個設計模式·策略模式
0. 專案地址
作者按:《每天一個設計模式》旨在初步領會設計模式的精髓,目前採用javascript
(靠這吃飯
)和python
(純粹喜歡
)兩種語言實現。誠然,每種設計模式都有多種實現方式,但此小冊只記錄最直截了當的實現方式 :)
- ofollow,noindex">本節課程式碼
- 《每天一個設計模式》地址
1. 什麼是策略模式?
策略模式定義:就是能夠把一系列“可互換的”演算法封裝起來,並根據使用者需求來選擇其中一種。
策略模式實現的核心就是:將演算法的使用和演算法的實現分離。演算法的實現交給策略類。演算法的使用交給環境類,環境類會根據不同的情況選擇合適的演算法。
2. 策略模式優缺點
在使用策略模式的時候,需要了解所有的“策略”(strategy)之間的異同點,才能選擇合適的“策略”進行呼叫。
3. 程式碼實現
3.1 python3實現
class Stragegy(): # 子類必須實現 interface 方法 def interface(self): raise NotImplementedError() # 策略A class StragegyA(): def interface(self): print("This is stragegy A") # 策略B class StragegyB(): def interface(self): print("This is stragegy B") # 環境類:根據使用者傳來的不同的策略進行例項化,並呼叫相關演算法 class Context(): def __init__(self, stragegy): self.__stragegy = stragegy() # 更新策略 def update_stragegy(self, stragegy): self.__stragegy = stragegy() # 呼叫演算法 def interface(self): return self.__stragegy.interface() if __name__ == "__main__": # 使用策略A的演算法 cxt = Context( StragegyA ) cxt.interface() # 使用策略B的演算法 cxt.update_stragegy( StragegyB ) cxt.interface()
3.2 javascript實現
// 策略類 const strategies = { A() { console.log("This is stragegy A"); }, B() { console.log("This is stragegy B"); } }; // 環境類 const context = name => { return strategies[name](); }; // 呼叫策略A context("A"); // 呼叫策略B context("B");
4. 參考
- 策略模式-Python四種實現方式
- Python設計模式 - 策略模式
- 《JavaScript設計模式和開發實踐》