Strategy Pattern in Python
Strategy Pattern in Pythonを、編集してオンライン実行できる実践例で学びます。
Strategy Patternとは?
Strategy Pattern in Pythonを、編集してオンライン実行できる実践例で学びます。
どのような場面で使う?
- 実績のある構造を使って、繰り返し発生するオブジェクト設計の問題を解決します。
- 責務を分離し、コードを拡張・テストしやすくします。
- チームでアーキテクチャを議論するときに共通の設計用語を使います。
サンプルコード
main.py
def regular_discount(total): return total
def member_discount(total): return total * 0.8
class Checkout:
# Strategy: inject the algorithm that is allowed to vary.
def __init__(self, discount_strategy):
self.discount_strategy = discount_strategy
def total(self, amount):
# Delegate the varying algorithm to the strategy.
return self.discount_strategy(amount)
checkout = Checkout(member_discount)
print(f"{checkout.total(15):.2f}")
期待される出力
12.00
仕組み
この例ではStrategy Pattern in Pythonを説明します。入力値を変更してコードの動作を確認してください。
値を変更し、PythonをインストールせずにCodeUtilityオンラインPythonコンパイラで実行できます。
練習問題
入力値と境界ケースを変更し、より大きなデータでも動作を確認してください。
- パターンの構造を保ったまま、サンプルの対象領域を置き換えてください。
- パターンをより単純な実装と比較し、トレードオフを説明してください。
- 別の実装を追加する前に、各参加要素のテストを書いてください。