📝 Strategy Design Pattern In Depth

📝 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:

  • Embed multiple algorithm implementations inside a single class.
  • Use long if-else or switch statements to choose which algorithm to apply.

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 ⚠️

  • Bloated Class → One class does too much.
  • Difficult to Maintain → Adding a new payment method requires editing the same class.
  • Violation of Open/Closed Principle → Existing code is constantly modified.
  • Hard to Test → Every algorithm is tangled inside one place.


3. The Solution ✅ – Strategy Pattern

The Strategy Pattern solves this by:

  • Defining a Strategy Interface for the algorithm family.
  • Creating Concrete Strategies for each implementation.
  • Letting the Context class use any strategy dynamically.

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);
}
        

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:

  • You can choose Driving, Walking, Cycling, or Public Transport as your route strategy.
  • The app’s context (maps) stays the same, but the strategy (route algorithm) changes dynamically.


6. When to Use Strategy Pattern? ✅

  • Multiple algorithms exist for the same task (sorting, payment methods, compression).
  • You want to switch algorithms at runtime without changing client code.
  • To avoid long conditional logic in classes.
  • When algorithms can vary independently from clients.


7. When NOT to Use Strategy Pattern? ❌

  • When there is only one fixed algorithm — strategy would overcomplicate.
  • When the algorithm logic is very small/simple — no need for extra classes.
  • When switching strategies frequently at runtime is unnecessary.
  • If performance is critical → strategy involves extra object creation & delegation.


8. Wrap-Up 🎯

The Strategy Design Pattern is a powerful way to:

  • Replace messy conditionals with clean, reusable algorithms.
  • Achieve flexibility, testability, and scalability.
  • Keep code aligned with the Open/Closed Principle.

👉 Next time you see multiple variations of an algorithm (payment, sorting, routing, compression, logging), think Strategy Pattern.

To view or add a comment, sign in

More articles by Suraj Singh

Others also viewed

Explore content categories