
- Python 設計模式教程
- Python 設計模式 - 首頁
- 簡介
- Python 設計模式 - 要點
- Model View Controller(MVC)模式
- Python 設計模式 - 單例
- Python 設計模式 - 工廠方法
- Python 設計模式 - 建造者
- Python 設計模式 - 原型
- Python 設計模式 - 外觀
- Python 設計模式 - 命令
- Python 設計模式 - 介面卡
- Python 設計模式 - 裝飾器
- Python 設計模式 - 代理
- 職責鏈模式
- Python 設計模式 - 觀察者
- Python 設計模式 - 狀態
- Python 設計模式 - 策略
- Python 設計模式 - 模板方法
- Python 設計模式 - 享元模式
- 抽象工廠
- 面向物件程式設計
- 面向物件概念實現
- Python 設計模式 - 迭代器
- 字典
- 連結串列資料結構
- Python 設計模式 - 集合
- Python 設計模式 - 佇列
- 字串和序列化
- Python 併發程式設計
- Python 設計模式 - 反模式
- 異常處理
- Python 設計模式資源
- 快速指南
- Python 設計模式 - 資源
- 討論
Python 設計模式 - 策略
策略模式是一種行為模式。策略模式的主要目標是讓客戶端能夠從不同的演算法或程式中進行選擇,以完成指定的任務。可以在沒有複雜性的情況下更換不同的演算法,以完成指定的任務。
當需要訪問外部資源時,可以使用此模式來提高靈活性。
如何實現策略模式?
下面展示的程式有助於實現策略模式。
import types class StrategyExample: def __init__(self, func = None): self.name = 'Strategy Example 0' if func is not None: self.execute = types.MethodType(func, self) def execute(self): print(self.name) def execute_replacement1(self): print(self.name + 'from execute 1') def execute_replacement2(self): print(self.name + 'from execute 2') if __name__ == '__main__': strat0 = StrategyExample() strat1 = StrategyExample(execute_replacement1) strat1.name = 'Strategy Example 1' strat2 = StrategyExample(execute_replacement2) strat2.name = 'Strategy Example 2' strat0.execute() strat1.execute() strat2.execute()
輸出
上述程式會生成以下輸出−

說明
它從這些函式中提供策略列表,這些函式執行該輸出。此行為模式的主要重點是行為。
廣告