策略模式是一種行為設計模式,它允許你在運行時動態地改變對象的行為。這種模式的核心思想是將一組相關的算法封裝在一起,并讓它們相互替換。
下面是使用 Python 實現策略模式的一個示例:
示例代碼
假設我們有一個簡單的購物車系統,其中不同的支付方式有不同的折扣策略。我們將使用策略模式來實現這一功能。
1. 定義抽象基類(策略接口)
from abc import ABC, abstractmethodclass PaymentStrategy(ABC):@abstractmethoddef pay(self, amount):pass
2. 具體策略實現
class CreditCardPayment(PaymentStrategy):def pay(self, amount):print(f"Paying ${amount} with credit card.")return f"${amount} paid using credit card."class PayPalPayment(PaymentStrategy):def pay(self, amount):print(f"Paying ${amount} with PayPal.")return f"${amount} paid using PayPal."
3. 上下文類
上下文類負責使用具體的策略來進行支付。
class ShoppingCart:def __init__(self, payment_strategy: PaymentStrategy):self._items = []self.payment_strategy = payment_strategydef add_item(self, item):self._items.append(item)def calculate_total(self):return sum(item['price'] for item in self._items)def checkout(self):total_amount = self.calculate_total()return self.payment_strategy.pay(total_amount)
4. 測試策略模式
if __name__ == "__main__":cart = ShoppingCart(CreditCardPayment())cart.add_item({'name': 'Shirt', 'price': 20})cart.add_item({'name': 'Pants', 'price': 30})print(cart.checkout())cart = ShoppingCart(PayPalPayment())cart.add_item({'name': 'Shoes', 'price': 50})cart.add_item({'name': 'Hat', 'price': 15})print(cart.checkout())
解釋
-
抽象基類(策略接口):
PaymentStrategy
類定義了一個抽象方法pay
,這是所有具體策略必須實現的方法。
-
具體策略實現:
CreditCardPayment
和PayPalPayment
分別實現了pay
方法,提供了不同的支付邏輯。
-
上下文類:
ShoppingCart
類持有一個payment_strategy
屬性,用于存放具體的支付策略。checkout
方法計算總金額并調用當前策略的pay
方法。
-
測試策略模式:
- 創建兩個
ShoppingCart
對象,分別使用CreditCardPayment
和PayPalPayment
策略。 - 添加商品并結算,觀察不同支付策略的結果。
- 創建兩個
通過這種方式,你可以靈活地切換不同的支付策略,而無需修改上下文類的代碼。這就是策略模式的主要優點之一。
完整可運行的代碼庫
from abc import ABC, abstractmethod# 抽象基類(策略接口)
class PaymentStrategy(ABC):@abstractmethoddef pay(self, amount):pass# 具體策略實現
class CreditCardPayment(PaymentStrategy):def pay(self, amount):print(f"Paying {amount} using credit card.")return f"{amount} paid using credit card."class PayPalPayment(PaymentStrategy):def pay(self, amount):print(f"Paying {amount} using PayPal.")return f"{amount} paid using PayPal."# 上下文類
class ShoppingCart:def __init__(self, payment_strategy: PaymentStrategy):self.items = []self.payment_strategy = payment_strategydef add_item(self, item):self.items.append(item)def remove_item(self, item):self.items.remove(item)def calculate_total(self):return sum(item['price'] for item in self.items)def checkout(self):total_amount = self.calculate_total()return self.payment_strategy.pay(total_amount)if __name__ == "__main__":cart = ShoppingCart(CreditCardPayment())cart.add_item({'name': 'Shirt', 'price': 20})cart.add_item({'name': 'Pants', 'price': 30})print(cart.checkout())cart = ShoppingCart(PayPalPayment())cart.add_item({'name': 'Shoes', 'price': 50})cart.add_item({'name': 'Hat', 'price': 15})print(cart.checkout())```