Python-design-patterns-strategy

提供:Dev Guides
移動先:案内検索

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

出力

上記のプログラムは、次の出力を生成します-

戦略パターン

説明

出力を実行する関数からの戦略のリストを提供します。 この行動パターンの主な焦点は行動です。