Suppose you want to extend the payment system to allow switching payment strategies at runtime based on user input, including invalid or unsupported methods. Which modification best supports this requirement while maintaining clean design?
AUse a factory method to get the strategy instance and inject it into PaymentProcessor; handle invalid methods by raising exceptions.
BKeep the strategy selection logic inside the PaymentProcessor's pay method with if-else chains.
CHardcode all payment methods inside PaymentProcessor and add a default fallback strategy for invalid inputs.
DRemove the strategy interface and implement all payment methods inside PaymentProcessor with switch-case.
Step-by-Step Solution
Step 1: Understand runtime strategy switching
Switching strategies at runtime requires decoupling strategy selection from the context and handling invalid inputs gracefully.
Step 2: Identify design that supports clean extensibility and error handling
Using a factory method to create strategy instances and injecting them into PaymentProcessor allows runtime flexibility and clean error handling via exceptions.
Final Answer:
Option A -> Option A
Quick Check:
Factory + DI + exceptions enable runtime switching and robustness [OK]
Quick Trick:Factory and DI enable runtime strategy switching with error handling [OK]
Common Mistakes:
MISTAKES
Hardcoding strategies or using conditionals inside context