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

輸出

上述程式會生成以下輸出−

Strategy Pattern

說明

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

廣告