Strategy Pattern - Definition and Core Problem
What Problem Does It Solve?
When you have multiple ways to perform an operation and need to switch between them dynamically, hardcoding all variations in a single class leads to bloated, rigid code that violates the Open/Closed Principle (OCP). The Strategy Pattern eliminates conditional logic for algorithm selection by delegating behavior to pluggable strategy objects.
Without Strategy Pattern
Consider a payment processing system. A naive implementation would use conditional statements:
method processPayment(amount, type):
if type == "CREDIT_CARD":
// credit card logic
else if type == "PAYPAL":
// PayPal logic
else if type == "CRYPTO":
// cryptocurrency logic
Problems: First, every new payment method requires modifying existing code (violates OCP). Second, the class grows exponentially with each variant. Third, testing becomes complex as all branches must be covered. Fourth, different teams cannot work independently on payment methods.
With Strategy Pattern
Each payment method becomes a separate strategy class implementing a common interface. The context switches strategies at runtime without knowing implementation details.