The before code uses if-else to handle payment methods, making it hard to add new methods. The after code defines a PaymentStrategy interface and separate classes for each payment method. PaymentProcessor uses a strategy instance to perform payment, enabling easy extension and cleaner code.
### Before: Without Strategy Pattern
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("Payment method not supported")
processor = PaymentProcessor()
processor.pay('credit_card', 100)
### After: With Strategy Pattern
from abc import ABC, abstractmethod
class PaymentStrategy(ABC):
@abstractmethod
def pay(self, amount):
pass
class CreditCardPay(PaymentStrategy):
def pay(self, amount):
print(f"Processing credit card payment of ${amount}")
class PayPalPay(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(CreditCardPay())
processor.pay(100)
processor = PaymentProcessor(PayPalPay())
processor.pay(200)