📝 Strategy Design Pattern In Depth
1. Introduction
The Strategy Design Pattern is a behavioral design pattern that enables you to define a family of algorithms, put each into its own class, and make them interchangeable at runtime.
💡 Core Idea:
Instead of hardcoding an algorithm, let the client choose which algorithm (strategy) to use at runtime.
It follows the Open/Closed Principle: Open for extension (new strategies), closed for modification (existing code doesn’t change).
2. The Problem ❌
Without the Strategy Pattern, developers often:
Example: Payment System without Strategy
class PaymentService {
public void pay(String method) {
if (method.equals("CreditCard")) {
// Process via Credit Card
} else if (method.equals("PayPal")) {
// Process via PayPal
} else if (method.equals("UPI")) {
// Process via UPI
}
}
}
Problems ⚠️
3. The Solution ✅ – Strategy Pattern
The Strategy Pattern solves this by:
This way, adding a new algorithm means just adding a new class — no changes to the context.
4. Example Code (Java)
Step 1: Strategy Interface
interface PaymentStrategy {
void pay(int amount);
}
Recommended by LinkedIn
Step 2: 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.");
}
}
class UPIPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Paid " + amount + " using UPI.");
}
}
Step 3: Context Class
class PaymentContext {
private PaymentStrategy strategy;
public void setPaymentStrategy(PaymentStrategy strategy) {
this.strategy = strategy;
}
public void checkout(int amount) {
strategy.pay(amount);
}
}
Step 4: Client Code
public class StrategyPatternDemo {
public static void main(String[] args) {
PaymentContext context = new PaymentContext();
context.setPaymentStrategy(new CreditCardPayment());
context.checkout(500);
context.setPaymentStrategy(new PayPalPayment());
context.checkout(1000);
context.setPaymentStrategy(new UPIPayment());
context.checkout(200);
}
}
Output:
Paid 500 using Credit Card.
Paid 1000 using PayPal.
Paid 200 using UPI.
5. Analogy 🌍
Think of navigation apps like Google Maps:
6. When to Use Strategy Pattern? ✅
7. When NOT to Use Strategy Pattern? ❌
8. Wrap-Up 🎯
The Strategy Design Pattern is a powerful way to:
👉 Next time you see multiple variations of an algorithm (payment, sorting, routing, compression, logging), think Strategy Pattern.