The before code uses if-else statements inside a single class to handle different payment methods, making it hard to add new methods. The after code defines a PaymentStrategy interface and separate classes for each payment method. The PaymentProcessor class delegates payment to the selected strategy, enabling easy extension and cleaner code.
### Before: Using conditionals to select behavior
class PaymentProcessor:
def pay(self, method, amount):
if method == 'credit_card':
print(f"Processing credit card payment of {amount}")
elif method == 'paypal':
print(f"Processing PayPal payment of {amount}")
else:
print(f"Unknown payment method: {method}")
# Usage
processor = PaymentProcessor()
processor.pay('credit_card', 100)
### After: Using Strategy pattern
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)
# Usage
processor = PaymentProcessor(CreditCardPayment())
processor.pay(100)
processor.strategy = PayPalPayment()
processor.pay(200)