strategy-pattern
π§ Concept
The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. This lets you change behavior at runtime without modifying the context class.
π§± Key Roles
Strategy (Interface)
Defines a common behavior (algorithm contract).
ConcreteStrategy
Implements a specific algorithm.
Context
Uses a Strategy to perform a task; can swap strategies dynamically.
π» Simple Java Example
// Strategy interface
interface PaymentStrategy {
void pay(int amount);
}
// Concrete strategies
class CreditCardPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Paid " + amount + " using Credit Card.");
}
}
class PayPalPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Paid " + amount + " using PayPal.");
}
}
// Context
class ShoppingCart {
private PaymentStrategy strategy;
void setPaymentStrategy(PaymentStrategy strategy) {
this.strategy = strategy;
}
void checkout(int amount) {
strategy.pay(amount);
}
}β Usage Example:
βοΈ Flow Summary (Step-by-Step)
Step
Action
Context (ShoppingCart)
Strategy Used
Output
1οΈβ£
setPaymentStrategy(CreditCard)
CreditCardPayment
CreditCardPayment
β
2οΈβ£
checkout(100)
β calls pay(100)
CreditCardPayment
"Paid 100 using Credit Card."
3οΈβ£
setPaymentStrategy(PayPal)
PayPalPayment
PayPalPayment
β
4οΈβ£
checkout(200)
β calls pay(200)
PayPalPayment
"Paid 200 using PayPal."
πͺ Summary
Encapsulates different algorithms behind a common interface.
Context delegates behavior to the chosen Strategy.
Easy to add new behaviors without touching existing code.
Promotes Open/Closed Principle (OCP).
π― Real-world Analogy
π³ Payment Methods β You can choose to pay by Credit Card, PayPal, or Cash, but the checkout process stays the same.
Last updated