DEV Community

Dev Cookies
Dev Cookies

Posted on

πŸ“ Day Five: Strategy Design Pattern in Java

πŸ” 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 ...
Enter fullscreen mode Exit fullscreen mode

πŸ”§ 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);
}
Enter fullscreen mode Exit fullscreen mode

βœ… 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);
    }
}
Enter fullscreen mode Exit fullscreen mode

βœ… 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);
    }
}
Enter fullscreen mode Exit fullscreen mode

πŸ’» 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("user@example.com"));
        context.pay(300);

        context.setPaymentStrategy(new CryptoPayment("0xA1B2C3D4E5F6"));
        context.pay(1000);
    }
}
Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ Output

Paid $500 using Credit Card: 1234-5678-9012-3456
Paid $300 using PayPal: user@example.com
Paid $1000 using Crypto Wallet: 0xA1B2C3D4E5F6
Enter fullscreen mode Exit fullscreen mode

🎯 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());
Enter fullscreen mode Exit fullscreen mode

🧠 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)         |
+----------------------+
Enter fullscreen mode Exit fullscreen mode

πŸš€ 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!

Top comments (0)