OOP & Design Patterns - Strategy Pattern - Replace Conditionals with Polymorphism
Given the following code snippet, what will be printed when executing the last two lines?
from abc import ABC, abstractmethod
class PaymentStrategy(ABC):
@abstractmethod
def pay(self, amount):
pass
class CreditCardStrategy(PaymentStrategy):
def pay(self, amount):
print(f"Processing credit card payment of ${amount}")
class UPIStrategy(PaymentStrategy):
def pay(self, amount):
print(f"Processing UPI payment of ${amount}")
class PaymentStrategyFactory:
@staticmethod
def get_strategy(method):
if method == 'CreditCard':
return CreditCardStrategy()
elif method == 'UPI':
return UPIStrategy()
else:
raise ValueError('Invalid payment method')
class PaymentProcessor:
def __init__(self, strategy: PaymentStrategy):
self.strategy = strategy
def pay(self, amount):
self.strategy.pay(amount)
processor = PaymentProcessor(PaymentStrategyFactory.get_strategy('UPI'))
processor.pay(100)
