Strategy Pattern

November 24, 202612 minutes

One trip, three routes. Learn how the Strategy pattern keeps the what in one place and lets the client swap the how, with diagrams, Java code, lambdas, and a narrated video.

You’re at home and need to get to the airport. The fastest route takes the highway, with a toll: 25 minutes. Avoiding tolls means back roads: 34 minutes. Walking is a completely different path. Same question, three different algorithms, and the app doesn’t decide which one is right: you do. How do you write a navigator that can do all three, and more later, without turning into a mess? The answer has a name: the Strategy pattern.

Prefer to watch? The narrated video above covers the same lesson (about 8 minutes). The article follows it section by section, with diagrams, a little extra depth, and the complete code.

One trip, three routes

Ask your navigation app for a route from home to the airport, and the honest answer is “which route?”:

The same request, a route from home to the airport, leads to three different algorithms depending on the user's choice: fastest takes the highway with a toll in 25 minutes, avoid tolls takes back roads in 34 minutes, walking takes paths in 2 hours 10 minutes. The same request, a route from home to the airport, leads to three different algorithms depending on the user's choice: fastest takes the highway with a toll in 25 minutes, avoid tolls takes back roads in 34 minutes, walking takes paths in 2 hours 10 minutes.
One job, several interchangeable ways to do it, picked from outside.

Same question (from here to there), three completely different algorithms, and the choice comes from the user, not from the navigator. That’s the shape the Strategy pattern is made for.

The obvious way: a switch on the mode

The natural first version is a mode: an enum with FASTEST, AVOID_TOLLS and WALKING, passed into the route method. Inside, a switch picks the algorithm:

enum Mode { FASTEST, AVOID_TOLLS, WALKING }

class Navigator {
    Route route(Point from, Point to, Mode mode) {
        switch (mode) {
            case FASTEST:     return fastestRoute(from, to);
            case AVOID_TOLLS: return noTollRoute(from, to);
            case WALKING:     return walkingRoute(from, to);
            default: throw new IllegalArgumentException("mode: " + mode);
        }
    }

    private Route fastestRoute(Point from, Point to) { /* 40 lines */ }
    private Route noTollRoute(Point from, Point to)  { /* 35 lines */ }
    private Route walkingRoute(Point from, Point to) { /* 30 lines */ }
}

Each of those helpers is a real algorithm: forty lines here, thirty-five there, thirty more. All of them live inside the navigator.

Inside the Navigator class, the route method switches on the mode and calls one of three private helpers, fastestRoute with 40 lines, noTollRoute with 35 lines and walkingRoute with 30 lines, so the navigator contains every algorithm. Inside the Navigator class, the route method switches on the mode and calls one of three private helpers, fastestRoute with 40 lines, noTollRoute with 35 lines and walkingRoute with 30 lines, so the navigator contains every algorithm.
The context contains every algorithm and picks one with a switch.

It works. And honestly, for a while, it’s fine. But the navigator now knows every single way of planning a route.

Why it breaks: every new mode touches everything

Then the product team asks for cycling. It’s just one more way to plan a route. Let’s count what we have to touch: a new value in the enum, a new case in the route switch, a new private helper, and the tests for the whole navigator.

But that’s not the only switch. The arrival-time calculation switches on the mode too:

Duration eta(Route r, Mode mode) {
    switch (mode) {
        case FASTEST:     return r.driveTime();
        case AVOID_TOLLS: return r.driveTime();
        case WALKING:     return r.walkTime();
        case CYCLING:     return r.bikeTime();   // easy to forget
        default: throw new IllegalArgumentException("mode: " + mode);
    }
}

Forget the new case there, and cycling throws an exception at run time, in front of a user.

Adding CYCLING ripples into five places: the Mode enum, the route switch, the eta switch, a new private helper inside Navigator, and NavigatorTest; forgetting the eta case causes a runtime exception. Adding CYCLING ripples into five places: the Mode enum, the route switch, the eta switch, a new private helper inside Navigator, and NavigatorTest; forgetting the eta case causes a runtime exception.
One new algorithm, five edits in one class.

And there’s a deeper problem. You can’t test the walking algorithm on its own, and nobody outside can add a new mode without editing the navigator itself. (When one change forces edits in many places like this, it’s the Shotgun Surgery smell; the scattered switch on a type code is its usual cause.)

When the how lives inside the class, every new how is surgery on that class.

The key insight: one interface, many algorithms

Think about a drill. The drill does one job: it turns. But you don’t buy a new drill for wood, metal and concrete. You swap the bit. Every bit fits the same chuck; you pick the right one for the job and change it from the outside, without opening the drill.

The analogy mapped onto code: the drill is the Navigator context, the chuck is the RouteStrategy interface, each bit is a concrete strategy such as Fastest, AvoidTolls or Walking, and you, choosing the bit, are the client. The analogy mapped onto code: the drill is the Navigator context, the chuck is the RouteStrategy interface, each bit is a concrete strategy such as Fastest, AvoidTolls or Walking, and you, choosing the bit, are the client.
The drill keeps the job; the bit supplies the how.

That’s the key insight: pull each algorithm out into its own class, behind one shared interface. Here it’s called RouteStrategy, with a single method, plan:

interface RouteStrategy {
    Route plan(Point from, Point to);
}

Fastest becomes a class, AvoidTolls becomes a class, Walking becomes a class, and each one fits the same socket:

class Fastest implements RouteStrategy {
    public Route plan(Point from, Point to) { /* highways, live traffic */ }
}

class AvoidTolls implements RouteStrategy {
    public Route plan(Point from, Point to) { /* skip toll roads */ }
}

class Walking implements RouteStrategy {
    public Route plan(Point from, Point to) { /* paths, stairs, shortcuts */ }
}

Notice that the strategies don’t know about each other, or about the navigator. Each one is a small, focused piece of code that does exactly one thing, and you can read it without scrolling past the other two.

The navigator keeps the what: plan a route. The strategy supplies the how.

Keep the what. Swap the how.

Building it: context, client, and swapping

Now the navigator itself. It holds one field, some RouteStrategy; it doesn’t know which. It gets a strategy in its constructor, a setter lets you replace it, and route() shrinks to one line: ask the strategy to plan.

class Navigator {
    private RouteStrategy strategy;

    Navigator(RouteStrategy strategy) { this.strategy = strategy; }

    void setStrategy(RouteStrategy strategy) { this.strategy = strategy; }

    Route route(Point from, Point to) {
        return strategy.plan(from, to);
    }
}

The client is the one who chooses. Start with Fastest and you get the highway, 25 minutes. Then the user taps “avoid tolls”: the client swaps the strategy, asks again, and gets the back roads, 34 minutes. The navigator didn’t change at all.

Navigator nav = new Navigator(new Fastest());
nav.route(home, airport);           // highway, 25 min

nav.setStrategy(new AvoidTolls());  // the user taps "avoid tolls"
nav.route(home, airport);           // back roads, 34 min
Sequence: the client creates a Navigator with Fastest; route delegates to Fastest.plan and returns the highway route; the client then calls setStrategy with AvoidTolls; route now delegates to AvoidTolls.plan and returns the back-roads route. Sequence: the client creates a Navigator with Fastest; route delegates to Fastest.plan and returns the highway route; the client then calls setStrategy with AvoidTolls; route now delegates to AvoidTolls.plan and returns the back-roads route.
The client swaps the strategy; the navigator just delegates.

Here’s the whole structure. The client creates a strategy and hands it to the navigator. The navigator only knows the interface, and each concrete strategy implements it. When cycling arrives, it’s one new class: no enum, no switches, and not a single line changed in the navigator.

class Cycling implements RouteStrategy {
    public Route plan(Point from, Point to) { /* bike lanes, no highways */ }
}
Class diagram: the Client creates a concrete strategy and hands it to the Navigator; the Navigator holds a RouteStrategy interface with plan; Fastest, AvoidTolls, Walking and the new Cycling implement it; Navigator is unchanged when Cycling is added. Class diagram: the Client creates a concrete strategy and hands it to the Navigator; the Navigator holds a RouteStrategy interface with plan; Fastest, AvoidTolls, Walking and the new Cycling implement it; Navigator is unchanged when Cycling is added.
Strategy: a context, one interface, interchangeable implementations, and a client that chooses.

And each strategy can be tested on its own: new Walking().plan(a, b) needs no navigator, no enum and no mocks.

The call strategy.plan(from, to) works because of dynamic dispatch: the compiler only sees the interface, and the runtime runs whichever class is plugged in.

Two design choices

1. What does a strategy get to see? Here, just the two points. If it needs more, like live traffic, pass that in too (plan(from, to, traffic)), or give the strategy its own source (a TrafficFeed in its constructor). Passing the whole context in is possible, but it couples every strategy to the navigator; prefer passing exactly the data the algorithm needs.

2. Set it once, or allow swapping? If users can change their minds, keep the setter. If the choice is fixed for the object’s life (say, from configuration), take it in the constructor only and make the field final. And since these strategies hold no state, one instance can be shared by every navigator in the app (a constant like static final RouteStrategy FASTEST = new Fastest();).

RoleIn this exampleResponsibility
ContextNavigatorkeeps the what; holds a strategy and delegates to it
StrategyRouteStrategythe one interface every algorithm implements
Concrete strategiesFastest, AvoidTolls, Walking, Cyclingone algorithm each, independent of each other
Clientthe app’s settings screenchooses (and swaps) the strategy

Strategies as lambdas (Java 8+)

Since Java 8 there’s a shortcut. RouteStrategy has exactly one abstract method, so it’s a functional interface, and a strategy can simply be a lambda: a shortest-path algorithm in one line, with no class at all. Or a method reference, like Planners::scenic:

@FunctionalInterface
interface RouteStrategy {
    Route plan(Point from, Point to);
}

Navigator nav = new Navigator((from, to) -> map.shortestPath(from, to));
nav.setStrategy(Planners::scenic);   // a method reference works too

The navigator can’t tell the difference; it still just calls plan. (@FunctionalInterface is optional; it makes the compiler reject a second abstract method.)

In fact, you use strategies every day. When you sort a list, the Comparator is the strategy. Sort by total, and the cheapest order comes first. Swap the comparator, and the same sort method puts the newest orders first:

List<Order> orders = loadOrders();
orders.sort(Comparator.comparing(Order::total));              // cheapest first
orders.sort(Comparator.comparing(Order::placedAt).reversed()); // newest first
The sorting algorithm in List.sort stays the same; plugging in a comparator by total gives the cheapest order first, and plugging in a comparator by placedAt reversed gives the newest order first. The sorting algorithm in List.sort stays the same; plugging in a comparator by total gives the cheapest order first, and plugging in a comparator by placedAt reversed gives the newest order first.
The sorting algorithm stays; the rule for comparing is what you swap.

Other JDK strategies you’ve probably passed around: Runnable for an executor, Predicate for removeIf, ThreadFactory, RejectedExecutionHandler.

Keep a full class when the strategy has its own state, several methods, or a name you want to see in your logs and settings. A lambda’s toString() is unreadable, and a configuration file can’t name it.

A realistic example: paying at checkout

The customer decides how to pay: with a card, or with a gift card. Each payment method is a strategy with one method, pay, and each one carries its own data: the card payment knows the card number, the gift card knows its balance.

interface PaymentMethod {
    Receipt pay(Money amount);
}

class CardPayment implements PaymentMethod {
    private final String cardNumber;
    CardPayment(String cardNumber) { this.cardNumber = cardNumber; }
    public Receipt pay(Money amount) { /* charge the card */ }
}

class GiftCard implements PaymentMethod {
    private Money balance;
    GiftCard(Money balance) { this.balance = balance; }
    public Receipt pay(Money amount) { /* subtract from the balance */ }
}

The checkout just calls pay with the cart’s total. It never asks which method it’s holding. So where did the decision go? There’s still one switch, but it lives at the edge, where the customer’s choice comes in, and it runs once:

class Checkout {
    Receipt complete(Cart cart, PaymentMethod method) {
        return method.pay(cart.total());   // never asks which method it is
    }
}

PaymentMethod chosen = switch (form.choice()) {   // the client picks, once
    case "card" -> new CardPayment(form.cardNumber());
    case "gift" -> new GiftCard(account.giftBalance());
    default     -> throw new IllegalArgumentException(form.choice());
};
checkout.complete(cart, chosen);
Sequence: the customer picks card on the form; the client code builds a CardPayment with the card number, once; it calls checkout.complete with the cart and the chosen method; Checkout calls pay with the total on the PaymentMethod, which returns a receipt, without Checkout knowing which method it is. Sequence: the customer picks card on the form; the client code builds a CardPayment with the card number, once; it calls checkout.complete with the cart and the chosen method; Checkout calls pay with the total on the PaymentMethod, which returns a receipt, without Checkout knowing which method it is.
The choice happens once, at the edge; the checkout just delegates.

That’s a common misconception: the Strategy pattern doesn’t remove every conditional. It moves the choice to one place, so the rest of the code can stop asking. A Map<String, Supplier<PaymentMethod>> registry can replace even that switch when the list of methods grows.

Strategy vs State

If you’ve seen the State pattern, this might look familiar. The class diagrams are identical: a context, an interface, and several implementations. The difference is who changes it.

Strategy: the client chooses AvoidTolls once and the Navigator keeps using it. State: the VendingMachine's current state replaces itself, from NoCoinState to HasCoinState to SoldOutState, as events happen. Strategy: the client chooses AvoidTolls once and the Navigator keeps using it. State: the VendingMachine's current state replaces itself, from NoCoinState to HasCoinState to SoldOutState, as events happen.
Same structure, opposite direction of control.
  • A strategy is chosen from outside, by the client. You pick “avoid tolls”, and it stays that way. The strategies don’t know each other.
  • A state is changed from inside. The vending machine moves from no coin, to has coin, to sold out, on its own, as things happen. And the states know about each other (they trigger the transitions).
StrategyState
Who picks the implementation?the client, from outsidethe object itself, as events happen
Do implementations know each other?nooften (they trigger transitions)
Changes over time?usually set once, swapped on requestconstantly
The question it answersHow should I do this task?What situation am I in?

Think of a GPS: you choose “avoid tolls”, and it stays that way. That’s a strategy. A traffic light changes on its own, and you never get a say. That’s state.

Strategy is chosen. State is lived.

One more neighbour worth knowing: Template Method varies an algorithm’s steps through inheritance (subclasses override hooks), while Strategy varies the whole algorithm through composition (you plug in an object). Strategy can be swapped at run time; Template Method is fixed when you pick the subclass.

When to use it (and when not to)

Use it when:

  • ✓ there are several ways to do the same job, chosen by the user or by configuration,
  • ✓ the same switch on an algorithm type keeps appearing,
  • ✓ you want to test and add algorithms without touching the context.

Skip it when:

  • ✗ there are only two tiny variants that never change: a plain if is fine,
  • ✗ there’s only ever one way to do the job,
  • ✗ the algorithm is a one-liner: use a lambda, not a class hierarchy.
Decision flowchart: if there is only one way to do the job, skip the pattern; if there are just two tiny variants that never change, use a plain if; otherwise use the Strategy pattern, as a lambda for one-line algorithms or as classes when they have state, several methods or need a name. Decision flowchart: if there is only one way to do the job, skip the pattern; if there are just two tiny variants that never change, use a plain if; otherwise use the Strategy pattern, as a lambda for one-line algorithms or as classes when they have state, several methods or need a name.
When Strategy pays for itself, and what shape to give it.

Recap

A switch on the mode puts every algorithm inside the context. Instead, put each algorithm behind one interface. The client chooses it, and the context just delegates. New algorithms become new classes, or even lambdas, and the context never has to change.

Recap chain: a switch on the mode inside the context is replaced by one interface, RouteStrategy; each algorithm becomes one class or lambda; the client chooses and the context delegates; a new algorithm is a new class with the context unchanged. Recap chain: a switch on the mode inside the context is replaced by one interface, RouteStrategy; each algorithm becomes one class or lambda; the client chooses and the context delegates; a new algorithm is a new class with the context unchanged.
Keep the what. Swap the how.
  • The context keeps the what and delegates the how to a strategy it holds.
  • Each strategy is one algorithm behind one interface, independent of the others.
  • The client chooses the strategy and may swap it at run time.
  • In modern Java a strategy is often just a lambda (Comparator is the classic one).
  • Strategy is chosen. State is lived.

Keep the what. Swap the how.

Complete code

For reference, the whole navigator with all four strategies, written out so it compiles (the route-finding itself is delegated to a RoadMap helper):

import java.util.List;

record Point(double lat, double lon) { }
record Route(List<Point> path, int minutes) { }

interface RoadMap {
    Route fastest(Point from, Point to);
    Route avoiding(String feature, Point from, Point to);
    Route walking(Point from, Point to);
    Route cycling(Point from, Point to);
}

@FunctionalInterface
interface RouteStrategy {
    Route plan(Point from, Point to);
}

class Fastest implements RouteStrategy {
    private final RoadMap map;
    Fastest(RoadMap map) { this.map = map; }
    public Route plan(Point from, Point to) { return map.fastest(from, to); }
}

class AvoidTolls implements RouteStrategy {
    private final RoadMap map;
    AvoidTolls(RoadMap map) { this.map = map; }
    public Route plan(Point from, Point to) { return map.avoiding("toll", from, to); }
}

class Walking implements RouteStrategy {
    private final RoadMap map;
    Walking(RoadMap map) { this.map = map; }
    public Route plan(Point from, Point to) { return map.walking(from, to); }
}

class Cycling implements RouteStrategy {
    private final RoadMap map;
    Cycling(RoadMap map) { this.map = map; }
    public Route plan(Point from, Point to) { return map.cycling(from, to); }
}

class Navigator {
    private RouteStrategy strategy;

    Navigator(RouteStrategy strategy) { this.strategy = strategy; }

    void setStrategy(RouteStrategy strategy) { this.strategy = strategy; }

    Route route(Point from, Point to) {
        return strategy.plan(from, to);
    }
}