Menu
Coddy logo textTech

Strategy パターン

CoddyのPythonジャーニー「オブジェクト指向プログラミング」セクションの一部。レッスン 48/64。

Strategy Patternはアルゴリズムのファミリーを定義し、それぞれをカプセル化して、相互に交換可能にします。クライアントコードを変更せずに、実行時にアルゴリズムを切り替えることができます。

異なる支払い方法に対応するシンプルな strategy クラスを以下に示します:

class CreditCard:
    def pay(self, amount):
        return f"Paid ${amount} with Credit Card"

class PayPal:
    def pay(self, amount):
        return f"Paid ${amount} with PayPal"

class Bitcoin:
    def pay(self, amount):
        return f"Paid ${amount} with Bitcoin"

各戦略は同じメソッド(pay)を実装しますが、動作は異なります。

戦略を使用するコンテキストクラスを作成します。

class ShoppingCart:
    def __init__(self):
        self.total = 0
        self.payment_strategy = None
    
    def add_item(self, price):
        self.total += price
    
    def set_payment_strategy(self, strategy):
        self.payment_strategy = strategy
    
    def checkout(self):
        return self.payment_strategy.pay(self.total)

コンテキストクラスは、異なる支払い戦略を切り替えられます。

strategy パターンを使用します:

cart = ShoppingCart()
cart.add_item(50)
cart.add_item(30)

# クレジットカード戦略を使用
cart.set_payment_strategy(CreditCard())
print(cart.checkout())

# PayPal戦略に切り替え
cart.set_payment_strategy(PayPal())
print(cart.checkout())

sorting strategiesを使用した別の例を作成しましょう:

class BubbleSort:
    def sort(self, data):
        return f"Bubble sorted: {sorted(data)}"

class QuickSort:
    def sort(self, data):
        return f"Quick sorted: {sorted(data)}"

class Sorter:
    def __init__(self, strategy):
        self.strategy = strategy
    
    def set_strategy(self, strategy):
        self.strategy = strategy
    
    def sort_data(self, data):
        return self.strategy.sort(data)

# 異なるソート戦略を使用する
numbers = [3, 1, 4, 1, 5]

sorter = Sorter(BubbleSort())
print(sorter.sort_data(numbers))

sorter.set_strategy(QuickSort())
print(sorter.sort_data(numbers))

出力:

Paid $80 with Credit Card
Paid $80 with PayPal
Bubble sorted: [1, 1, 3, 4, 5]
Quick sorted: [1, 1, 3, 4, 5]

要点:Strategy パターンを使うと、実行時にアルゴリズムを切り替えられます。同じインターフェースを持つ異なる戦略を定義し、コンテキストクラスにどれを使用するか選択させます。これにより、既存のコードを変更せずに新しいアルゴリズムを追加でき、コードを柔軟かつ拡張しやすくできます。

challenge icon

チャレンジ

中級

ショッピングシステム用の新しい BitcoinPayment strategy を実装してください。

あなたの課題は次のとおりです。

  1. PaymentStrategy を実装する BitcoinPayment class を作成する
    • constructor で wallet_address を受け取るようにする
    • pay method は、X が amount、Y が wallet address を表す形式で、正確に Paying $X using Bitcoin wallet: Y を出力する
    • pay method は、出力後に True を返す
  2. 次の処理を行う main function を記述する
    • shopping cart を作成する
    • $1200 の Laptop と $100 の Headphones を cart に追加する
    • wallet address "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa" を指定して BitcoinPayment を作成する
    • この payment strategy を cart に設定する
    • checkout method を呼び出す

スターターコードには、末尾に if __name__ == "__main__": がすでに含まれています。これを自分で追加する必要はありません。これは、ファイルが直接実行された場合(別のモジュールから import された場合ではなく)のみ main() function が実行されるようにする Python の慣例です。単に main() function を定義すれば、提供されているブロックが自動的に呼び出します。

レッスンの例で示されているものと同じ構造に従ってください。

自分で試してみよう

from abc import ABC, abstractmethod

class PaymentStrategy(ABC):
    @abstractmethod
    def pay(self, amount):
        pass

class CreditCardPayment(PaymentStrategy):
    def __init__(self, card_number, expiry_date, cvv):
        self.card_number = card_number
        self.expiry_date = expiry_date
        self.cvv = cvv
        
    def pay(self, amount):
        print(f"Paying ${amount} using Credit Card: {self.card_number}")
        return True

class PayPalPayment(PaymentStrategy):
    def __init__(self, email, password):
        self.email = email
        self.password = password
        
    def pay(self, amount):
        print(f"Paying ${amount} using PayPal account: {self.email}")
        return True

class ShoppingCart:
    def __init__(self):
        self.items = []
        self.payment_strategy = None
    
    def add_item(self, item, price):
        self.items.append({"item": item, "price": price})
    
    def set_payment_strategy(self, payment_strategy):
        self.payment_strategy = payment_strategy
    
    def checkout(self):
        total = sum(item["price"] for item in self.items)
        if self.payment_strategy:
            return self.payment_strategy.pay(total)
        else:
            raise ValueError("No payment strategy set")

# Create your BitcoinPayment strategy class here


if __name__ == "__main__":
    main()
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

オブジェクト指向プログラミングのすべてのレッスン

自分で練習してみよう: Pythonオンラインコンパイラ