The before code mixes payment logic in one method, making it hard to add new methods. The after code uses the strategy pattern to separate payment methods into classes implementing a common interface. PaymentProcessor delegates payment to the selected strategy, enabling easy extension and cleaner code.
### Before: tightly coupled payment handling
class PaymentHandler:
def pay(self, method, amount):
if method == 'credit_card':
# process credit card payment
print(f"Processing credit card payment of {amount}")
elif method == 'paypal':
# process paypal payment
print(f"Processing PayPal payment of {amount}")
else:
raise ValueError("Unsupported payment method")
handler = PaymentHandler()
handler.pay('credit_card', 100)
### After: strategy pattern for payment handling
from abc import ABC, abstractmethod
class PaymentStrategy(ABC):
@abstractmethod
def pay(self, amount):
pass
class CreditCardPayment(PaymentStrategy):
def pay(self, amount):
print(f"Processing credit card payment of {amount}")
class PayPalPayment(PaymentStrategy):
def pay(self, amount):
print(f"Processing PayPal payment of {amount}")
class PaymentProcessor:
def __init__(self, strategy: PaymentStrategy):
self.strategy = strategy
def pay(self, amount):
self.strategy.pay(amount)
processor = PaymentProcessor(CreditCardPayment())
processor.pay(100)
processor.strategy = PayPalPayment()
processor.pay(200)