🔍 What is the Strategy Pattern?

The Strategy Pattern is a behavioral design pattern that enables selecting an algorithm at runtime — encapsulating different strategies (algorithms) and making them interchangeable.


✅ When Should You Use It?

  • When you need multiple variations of an algorithm.
  • When you want to decouple the behavior from the context class.
  • When you want to follow the Open-Closed Principle — extend behavior without modifying existing code.

🧠 Real-World Analogy

Think of a navigation app 🚗 like Google Maps. Based on your need, you can choose:

  • Drive
  • Walk
  • Cycle
  • Public Transit

Each of these is a strategy to reach the same goal: your destination.


🧱 Structure

+------------------+         +-----------------------+
|     Context      |<------->|      Strategy         |
+------------------+         +-----------------------+
| - strategy: S    |         | +execute(): void      |
| +setStrategy(S)  |         +-----------------------+
| +executeStrategy()|             /        |        \
+------------------+     ConcreteStrategyA ConcreteStrategyB ...

🔧 Example: Payment System with Strategy Pattern

We’ll create a PaymentStrategy interface with multiple payment types.


✅ 1. Strategy Interface

public interface PaymentStrategy {
    void pay(int amount);
}

✅ 2. Concrete Strategies

public class CreditCardPayment implements PaymentStrategy {
    private String cardNumber;

    public CreditCardPayment(String cardNumber) {
        this.cardNumber = cardNumber;
    }

    @Override
    public void pay(int amount) {
        System.out.println("Paid $" + amount + " using Credit Card: " + cardNumber);
    }
}

public class PayPalPayment implements PaymentStrategy {
    private String email;

    public PayPalPayment(String email) {
        this.email = email;
    }

    @Override
    public void pay(int amount) {
        System.out.println("Paid $" + amount + " using PayPal: " + email);
    }
}

public class CryptoPayment implements PaymentStrategy {
    private String walletAddress;

    public CryptoPayment(String walletAddress) {
        this.walletAddress = walletAddress;
    }

    @Override
    public void pay(int amount) {
        System.out.println("Paid $" + amount + " using Crypto Wallet: " + walletAddress);
    }
}

✅ 3. Context Class

public class PaymentContext {
    private PaymentStrategy strategy;

    public void setPaymentStrategy(PaymentStrategy strategy) {
        this.strategy = strategy;
    }

    public void pay(int amount) {
        if (strategy == null) {
            throw new IllegalStateException("Payment Strategy not set");
        }
        strategy.pay(amount);
    }
}

💻 Client Code

public class StrategyDemo {
    public static void main(String[] args) {
        PaymentContext context = new PaymentContext();

        context.setPaymentStrategy(new CreditCardPayment("1234-5678-9012-3456"));
        context.pay(500);

        context.setPaymentStrategy(new PayPalPayment("[email protected]"));
        context.pay(300);

        context.setPaymentStrategy(new CryptoPayment("0xA1B2C3D4E5F6"));
        context.pay(1000);
    }
}

🧪 Output

Paid $500 using Credit Card: 1234-5678-9012-3456
Paid $300 using PayPal: [email protected]
Paid $1000 using Crypto Wallet: 0xA1B2C3D4E5F6

🎯 Benefits

✅ Replaces complex if-else or switch logic

✅ Supports Open-Closed Principle

✅ Easier to test, maintain, and extend

✅ Promotes flexible design


⚙️ Java Libraries Using Strategy

  • Comparator in Collections.sort() uses Strategy pattern.
Collections.sort(list, new MyCustomComparator());

🧠 Summary

Feature Strategy Pattern
Pattern Type Behavioral
Main Idea Define a family of algorithms, encapsulate each, and make them interchangeable
Use Cases Payment processing, file compression, data encryption, sorting, etc.

🧱 Want a UML for reference? Here’s a quick text version:

+----------------------+
|    PaymentStrategy   |<-----------+
+----------------------+            |
| +pay(amount): void   |            |
+----------------------+            |
        ^                           |
        |                           |
+-------------------+   +--------------------+
| CreditCardPayment |   |   PayPalPayment    |
+-------------------+   +--------------------+
        ^                           ^
        |                           |
      (Used by)                (Used by)
        |                           |
+----------------------+
|    PaymentContext     |
+----------------------+
| -strategy: Strategy  |
| +setStrategy(s)      |
| +pay(amount)         |
+----------------------+

🚀 Up Next for Day 6: We’ve done Strategy, Decorator, Singleton, Factory, Builder — want to explore Adapter, Chain of Responsibility, State, or Facade next?

Let me know and I’ll get that day rolling!