Skip to main content

Command Palette

Search for a command to run...

Week 20 – Behavioral Design Pattern: Strategy

Design Patterns Demystified Series

Updated
5 min read
Week 20 – Behavioral Design Pattern: Strategy

This week, we’re exploring the Strategy Pattern, a behavioral design pattern that allows you to switch between different algorithms or behaviors at runtime.

It’s commonly used in navigation apps, payment systems, sorting mechanisms, discount engines, tax calculations, and more.

Let’s understand it with a simple Maps route analogy and clean Java code.

🧠 What is the Strategy Pattern?

The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable.

Instead of using large if-else or switch statements, the object delegates its behavior to a strategy object.

Each strategy:

  • Implements a common interface

  • Encapsulates a specific algorithm

  • Can be swapped at runtime

In simple terms:

One context → multiple strategies → behavior changes manually at runtime

🗺️ Real-World Analogy: Maps Navigation

Imagine you’re using Maps to go from:

College → Library

You can choose different travel modes:

  • 🚗 Car → Fastest route

  • 🚴 Bike → Safest route

  • 🚶 Walk → Shortest path

The destination is the same.

But the route calculation algorithm changes depending on what you select.

Maps:

  • Doesn’t rewrite its navigation system

  • Doesn’t use huge conditional logic

  • Simply switches the routing strategy

That’s exactly how the Strategy Pattern works.

💻 Let’s Translate That Into Code

Strategy Interface

interface RouteStrategy {
    void buildRoute(String from, String to);
}

This interface defines a common behavior:

  • buildRoute() → calculates the route

Concrete Strategies

Car Route Strategy

class CarRouteStrategy implements RouteStrategy {
    @Override
    public void buildRoute(String from, String to) {
        System.out.println("Calculating fastest route by CAR from " + from + " to " + to);
    }
}

Bike Route Strategy

class BikeRouteStrategy implements RouteStrategy {
    @Override
    public void buildRoute(String from, String to) {
        System.out.println("Calculating safest route by BIKE from " + from + " to " + to);
    }
}

Walk Route Strategy

class WalkRouteStrategy implements RouteStrategy {
    @Override
    public void buildRoute(String from, String to) {
        System.out.println("Calculating shortest WALK route from " + from + " to " + to);
    }
}

Each strategy:

  • Implements the same interface

  • Provides a different algorithm

Context — Navigator

class Navigator {
    private RouteStrategy routeStrategy;
    // Set strategy at runtime
    public void setRouteStrategy(RouteStrategy routeStrategy) {
        this.routeStrategy = routeStrategy;
    }
    public void navigate(String from, String to) {
        if (routeStrategy == null) {
            throw new IllegalStateException("Route strategy is not set!");
        }
        routeStrategy.buildRoute(from, to);
    }
}

The context:

  • Holds a reference to a strategy

  • Delegates route calculation to it

  • Does not know how the route is calculated

Client Code

public class StrategyPatternDemo {
    public static void main(String[] args) {
    Navigator navigator = new Navigator();
        String from = "College";
        String to = "Library";
        // Choose CAR strategy
        navigator.setRouteStrategy(new CarRouteStrategy());
        navigator.navigate(from, to);
        // Switch to BIKE strategy
        navigator.setRouteStrategy(new BikeRouteStrategy());
        navigator.navigate(from, to);
        // Switch to WALK strategy
        navigator.setRouteStrategy(new WalkRouteStrategy());
        navigator.navigate(from, to);
    }
}

✅ Output

Calculating fastest route by CAR from College to Library
Calculating safest route by BIKE from College to Library
Calculating shortest WALK route from College to Library

🎯 What This Demonstrates

This example shows the core idea of the Strategy Pattern:

  • Navigator is the context

  • CarRouteStrategy, BikeRouteStrategy, and WalkRouteStrategy are the strategies

The navigator:

  • Delegates behavior to the selected strategy

  • Allows switching algorithms at runtime

  • Avoids conditional logic

  • Keeps code clean and extensible

So the behavior changes based on the selected strategy — not internal state.


🧩 Why Use the Strategy Pattern?

Advantages

  • Eliminates large conditional statements

  • Encapsulates algorithms separately

  • Makes code cleaner and more maintainable

  • Follows the Open/Closed Principle

  • Easy to add new strategies

  • Allows runtime flexibility

When to Use It

  • When you have multiple ways to perform a task

  • When you want to avoid large if-else blocks

  • When algorithms may change independently

  • When behavior must change dynamically

🌍 Real-World Use Cases

  • Navigation apps (fastest, shortest, eco route)

  • Payment processing (Credit Card, UPI, PayPal)

  • Sorting algorithms

  • Discount calculation systems

  • Tax calculation engines

  • Data compression techniques


🔜 Next Up: Template Method Pattern!

Next week, we’ll explore how the Template Method Pattern defines the skeleton of an algorithm and lets subclasses override specific steps — while keeping the overall structure intact.

Stay tuned as we break it down with beginner-friendly code examples, relatable analogies, and real-world use cases. We’ll help you write cleaner, more flexible, and more maintainable code — one pattern at a time.

✅ Call to Action (CTA)

🚀 Want to level up your design pattern skills?
Subscribe or follow the series — we’ll walk through each pattern with examples, analogies, and real-world code you can use today.


Note: AI-generated image

Design Patterns

Part 21 of 25

Let’s be honest—most devs would rather code than study design patterns. They seem academic and full of jargon. But this guide is different: plain language, real-life analogies, and practical examples that make your code smarter, cleaner, and scalable

Up next

Week 21 – Behavioral Design Pattern: Template Method

Design Patterns Demystified Series