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.
Ask your navigation app for a route from home to the airport, and the honest answer is “which route?”:
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 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.
It works. And honestly, for a while, it’s fine. But the navigator now knows every single way of planning a route.
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.
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.
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.
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.
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 minHere’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 */ }
}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.
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();).
| Role | In this example | Responsibility |
|---|---|---|
| Context | Navigator | keeps the what; holds a strategy and delegates to it |
| Strategy | RouteStrategy | the one interface every algorithm implements |
| Concrete strategies | Fastest, AvoidTolls, Walking, Cycling | one algorithm each, independent of each other |
| Client | the app’s settings screen | chooses (and swaps) the strategy |
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 tooThe 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 firstOther 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.
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);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.
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 | State | |
|---|---|---|
| Who picks the implementation? | the client, from outside | the object itself, as events happen |
| Do implementations know each other? | no | often (they trigger transitions) |
| Changes over time? | usually set once, swapped on request | constantly |
| The question it answers | How 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.
Use it when:
switch on an algorithm type keeps appearing,Skip it when:
if is fine,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.
Comparator is the classic one).Keep the what. Swap the how.
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);
}
}