鍍金池/ 教程/ Python/ 策略設(shè)計模式
反模式
隊列
適配器設(shè)計模式
享元設(shè)計模式
Python設(shè)計模式
工廠模式
模板設(shè)計模式
構(gòu)建器(Builder)設(shè)計模式
Python設(shè)計模式概要
命令設(shè)計模式
Python設(shè)計模式簡介
觀察者設(shè)計模式
代理設(shè)計模式
異常處理
責(zé)任鏈設(shè)計模式
字典實現(xiàn)
抽象工廠設(shè)計模式
Python并發(fā)(多線程)
策略設(shè)計模式
門面(Facade)設(shè)計模式
原型設(shè)計模式
迭代器設(shè)計模式
集合
單例模式
列表數(shù)據(jù)結(jié)構(gòu)
狀態(tài)設(shè)計模式
模型視圖控制器(MVC)模式
裝飾器設(shè)計模式
面向?qū)ο蟾拍畹膶崿F(xiàn)
面向?qū)ο笤O(shè)計模式
字符串和序列化

策略設(shè)計模式

策略模式是一種行為模式。 策略模式的主要目標(biāo)是使客戶能夠從不同的算法或程序中進行選擇以完成指定的任務(wù)。 不同的算法可以交換出入,而不會對上述任務(wù)產(chǎn)生任何影響。

當(dāng)訪問外部資源時,可以使用此模式來提高靈活性。

如何實施策略模式?

有關(guān)如何使用Python實現(xiàn)策略模式,請參考以下代碼 -

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()

執(zhí)行上述程序生成以下輸出 -

解釋說明

它提供執(zhí)行輸出的函數(shù)的策略列表。 這種行為模式的主要焦點是行為。