Strategy pattern
Swap one algorithm for another at run time by putting each behind a common interface. Full Java and Python code, how it differs from State and Template Method, and when a plain function is enough.
On this page
The problem: one method that does everything
A navigation app plans routes by car, by bike and on foot. The first version is one method with a branch per mode:
Route buildRoute(Point a, Point b, String mode) {
if (mode.equals("car")) {
// 60 lines: highways, traffic, tolls
return carRoute;
} else if (mode.equals("bike")) {
// 50 lines: bike lanes, hills
return bikeRoute;
} else if (mode.equals("walk")) {
// 40 lines: footpaths, stairs
return walkRoute;
}
throw new IllegalArgumentException("Unknown mode: " + mode);
}
It works, until it changes. Every new mode makes the method longer. Every change to the car rules means editing a method that also holds the bike and walking rules, so all three need re-testing. Two developers adding two modes at once will collide in the same file.
One method, every travel mode
- A navigation app plans routes by car, bike or on foot. The quick way is one big method: if car, do this; else if bike, do that. Every new travel mode makes that method longer, and every change risks breaking the others.
The underlying issue: several ways of doing the same job are tangled together, and the code that uses a route is mixed with the code that computes one.
The idea: one interface, one class per algorithm
The Strategy pattern pulls each algorithm out into its own class behind a shared interface. The class that needs a route, the context, holds one strategy and asks it to do the work. It neither knows nor cares which one it holds.
The context holds a strategy and can swap it
- The Strategy pattern pulls each algorithm into its own class behind one interface, RouteStrategy. The Navigator, called the context, holds one strategy and simply asks it for a route.
- Because the strategy is just a part the Navigator holds, you can swap it while the app runs: it starts raining, so setStrategy(new CarRoute()). Same Navigator, different behaviour.
The three roles:
| Role | In this example | Responsibility |
|---|---|---|
| Strategy (interface) | RouteStrategy | Declares the one operation all algorithms share: build(a, b) |
| Concrete strategies | CarRoute, BikeRoute, WalkRoute | Each implements the algorithm its own way |
| Context | Navigator | Holds a strategy, delegates to it, lets callers swap it |
Build it step by step
1. The interface. One method that every algorithm will implement.
2. One class per algorithm. Each is small, focused and testable on its own.
3. The context. It receives a strategy (usually in its constructor) and delegates.
4. The client picks a strategy and can change it later.
// 1. The strategy interface
public interface RouteStrategy {
Route build(Point from, Point to);
}
// 2. Concrete strategies
public class CarRoute implements RouteStrategy {
public Route build(Point from, Point to) {
// highways, live traffic, tolls
return new Route(List.of(from, to), Duration.ofMinutes(12));
}
}
public class BikeRoute implements RouteStrategy {
public Route build(Point from, Point to) {
// bike lanes, avoid steep hills
return new Route(List.of(from, to), Duration.ofMinutes(25));
}
}
public class WalkRoute implements RouteStrategy {
public Route build(Point from, Point to) {
// footpaths, stairs allowed
return new Route(List.of(from, to), Duration.ofMinutes(55));
}
}
// 3. The context
public class Navigator {
private RouteStrategy strategy;
public Navigator(RouteStrategy strategy) { this.strategy = Objects.requireNonNull(strategy); }
public void setStrategy(RouteStrategy strategy) { this.strategy = Objects.requireNonNull(strategy); }
public Route route(Point from, Point to) {
return strategy.build(from, to); // delegate: no if/else here
}
}
// 4. The client
Navigator nav = new Navigator(new BikeRoute());
Route r1 = nav.route(home, office);
// it starts raining…
nav.setStrategy(new CarRoute());
Route r2 = nav.route(home, office);from abc import ABC, abstractmethod
from dataclasses import dataclass
@dataclass
class Route:
points: list
minutes: int
# 1. The strategy interface
class RouteStrategy(ABC):
@abstractmethod
def build(self, start, end) -> Route: ...
# 2. Concrete strategies
class CarRoute(RouteStrategy):
def build(self, start, end):
return Route([start, end], 12) # highways, live traffic, tolls
class BikeRoute(RouteStrategy):
def build(self, start, end):
return Route([start, end], 25) # bike lanes, avoid steep hills
class WalkRoute(RouteStrategy):
def build(self, start, end):
return Route([start, end], 55) # footpaths, stairs allowed
# 3. The context
class Navigator:
def __init__(self, strategy: RouteStrategy):
self.strategy = strategy
def set_strategy(self, strategy: RouteStrategy):
self.strategy = strategy
def route(self, start, end) -> Route:
return self.strategy.build(start, end) # delegate: no if/else here
# 4. The client
nav = Navigator(BikeRoute())
r1 = nav.route(home, office)
nav.set_strategy(CarRoute()) # it starts raining…
r2 = nav.route(home, office)Adding a new mode touches nothing old
Adding a bus route: one new class, nothing edited
- Each strategy is small and focused, so it’s easy to test alone. Adding a bus mode is one new class; the Navigator and the other routes don’t change. That’s open/closed again, built from composition instead of if/else.
A bus mode is one new class that implements RouteStrategy. Navigator, CarRoute, BikeRoute and WalkRoute are not opened. That is the open/closed principle in practice: open for extension, closed for modification. It also follows the single responsibility principle: each class has one reason to change.
But someone still has to choose
The if/else hasn't completely vanished: somewhere, user input like "bike" must become a BikeRoute. Keep that choice in one place, usually a map (a registry) or a small factory, rather than scattered through the code.
public final class Routes {
private static final Map<String, Supplier<RouteStrategy>> BY_MODE = Map.of(
"car", CarRoute::new,
"bike", BikeRoute::new,
"walk", WalkRoute::new
);
public static RouteStrategy forMode(String mode) {
Supplier<RouteStrategy> s = BY_MODE.get(mode);
if (s == null) throw new IllegalArgumentException("Unknown mode: " + mode);
return s.get();
}
}
Navigator nav = new Navigator(Routes.forMode(request.mode()));ROUTES = {"car": CarRoute, "bike": BikeRoute, "walk": WalkRoute}
def route_for(mode: str) -> RouteStrategy:
try:
return ROUTES[mode]()
except KeyError:
raise ValueError(f"Unknown mode: {mode}") from None
nav = Navigator(route_for(request.mode))How does a strategy get the data it needs?
Two choices, and interviewers sometimes ask which you'd pick:
- Pass what it needs as parameters (
build(from, to)): the strategy stays independent of the context and easy to test. Prefer this. - Pass the context itself (
build(navigator)): the strategy can read anything it wants, which is convenient when strategies need very different data, but it couples every strategy to the context's API.
Configuration that belongs to one strategy (a toll preference, an API key) goes in that strategy's constructor, not in the shared interface.
Strategies with no class at all
When a strategy is a single method with no state, a whole class is ceremony. In Java, any interface with one abstract method can be a lambda; in Python, functions are already objects you can pass around.
@FunctionalInterface
public interface RouteStrategy {
Route build(Point from, Point to);
}
Navigator nav = new Navigator((a, b) -> new Route(List.of(a, b), Duration.ofMinutes(30)));
// You already use this every day: Comparator is a strategy
names.sort(Comparator.comparing(String::length));from typing import Callable
RouteFn = Callable[[object, object], Route] # any function (start, end) -> Route
class Navigator:
def __init__(self, build: RouteFn):
self.build = build
def route(self, start, end) -> Route:
return self.build(start, end)
def scenic(start, end):
return Route([start, "viewpoint", end], 40)
nav = Navigator(scenic) # a plain function is the strategy
nav = Navigator(lambda a, b: Route([a, b], 30))
sorted(names, key=len) # you already use this: key= is a strategyA third lightweight option in Java is an enum whose constants implement the interface (enum Shipping implements CostRule { STANDARD { … }, EXPRESS { … } }), which gives you a closed, named set with no registry.
Use a lambda or function for small, stateless strategies. Use a class when the strategy has configuration (an API key, a toll preference), several methods, or needs its own tests and documentation.
Strategies you already use
- Strategies are everywhere: the comparator you pass to sort, payment methods at checkout, compression formats, pricing rules. Whenever you see “the same job, done different ways, chosen at run time”, think strategy.
Strategy, State, Template Method: how they differ
These three look alike on a class diagram. Interviewers like to ask the difference.
| Strategy | State | Template Method | |
|---|---|---|---|
| What varies | The algorithm for one job | Behaviour that depends on the object's current state | Some steps inside a fixed algorithm |
| Who chooses | The client, from outside | The object itself, as it changes state | Fixed by the subclass you instantiate |
| Do the variants know each other? | No, they are independent | Often: a state may choose the next state (or the context decides the transitions) | No |
| Mechanism | Composition: context has a strategy | Composition: context has a current state | Inheritance: subclass overrides steps |
| Example | Pay by card, PayPal or UPI | Vending machine: Idle → HasCoin → Dispensing | Data export: open → write rows → close, where "write rows" is CSV or JSON |
Two more look-alikes: Command also wraps behaviour in an object, but a command is a request to do something later (it can be queued, logged or undone), while a strategy is a way of doing a job the context performs now. Bridge splits an abstraction from its implementation so both can vary; structurally it is a strategy chosen once at construction and kept for life.
A useful rule of thumb: if the variants replace each other on their own, it's State. If the caller picks one, it's Strategy. If the variants differ only in a few steps of the same recipe, it's Template Method.
When not to use it
In the interview
An online shop offers discounts: a percentage off, a fixed amount off, and "buy 2 get 1 free" on a product. Marketing invents a new rule every month. Sketch the classes (names and one method each) and the line of code where a cart applies a discount.
Compare with our answer
public interface DiscountRule {
Money apply(Cart cart); // returns the discount amount
}
public class PercentOff implements DiscountRule {
private final int percent;
public PercentOff(int percent) { this.percent = percent; }
public Money apply(Cart cart) { return cart.subtotal().times(percent).dividedBy(100); }
}
public class AmountOff implements DiscountRule {
private final Money amount;
public AmountOff(Money amount) { this.amount = amount; }
public Money apply(Cart cart) { return Money.min(amount, cart.subtotal()); }
}
public class BuyTwoGetOne implements DiscountRule {
private final String sku;
public BuyTwoGetOne(String sku) { this.sku = sku; }
public Money apply(Cart cart) {
int free = cart.quantityOf(sku) / 3;
return cart.priceOf(sku).times(free);
}
}
// in Cart / Checkout
Money total = subtotal().minus(discount.apply(this));
A strong answer mentions: one interface with one method · one class per rule with its own configuration in the constructor · the cart delegating instead of branching · a way to choose rules in one place · what happens when rules stack.
Real details to raise: use a decimal money type and round once at the end; validate that a percentage is 0–100; and if rules stack, the order matters (10% off then $5 off is not the same as $5 off then 10% off), so make the order explicit.
The cart (the context) holds a DiscountRule. A new monthly rule is a new class. If several rules can stack, hold a List<DiscountRule> and add the results, or wrap them in a CompositeDiscount that itself implements DiscountRule.
- Intent: a family of interchangeable algorithms behind one interface; the client picks one, and can swap it at run time.
- Roles: Strategy interface · concrete strategies · context that has a strategy and delegates.
- Wins: no growing if/else; each algorithm tested alone; new behaviour = new class (open/closed).
- Keep the choice in one place: a map or factory from key → strategy.
- Lightweight form: lambdas / functions for small stateless strategies (Comparator,
key=). - Not State: states switch themselves; strategies are chosen by the caller. Not Template Method: that varies steps via inheritance.
- Skip it for two fixed branches or when a lookup table of values is enough.
Marketing now wants discounts to stack, with a rule that "percentage discounts always apply before fixed-amount ones", and a cap so the total discount never exceeds 50% of the subtotal. How does your design change?
Compare with our answer
A strong answer mentions: a CompositeDiscount (itself a DiscountRule) that holds a list · sorting or grouping rules by kind so percentages run first · applying each rule to the running total rather than the original subtotal · enforcing the 50% cap once, in the composite, not in every rule · tests for the ordering and the cap.
1. A food-delivery app calculates the delivery fee differently on normal days, rainy days and festival days, and the business team adds new rules often. Which design fits best?
The fee rule varies on its own and changes often, so each rule becomes a strategy. Subclassing Order ties the fee to the order type and multiplies classes; a branch per rule grows without end.
2. What is the main difference between Strategy and State?
Both use composition and look the same on a diagram. The difference is who triggers the change: states transition themselves, strategies are picked from outside.
3. After introducing Strategy, the code still has if (mode.equals("car")) return new CarRoute(); …. What is the best way to handle that?
Something has to turn input into a strategy. Centralising that choice in one registry or factory keeps the rest of the code free of branches. An enum helps, but not if the branches stay scattered.
4. Which situation is the weakest case for the Strategy pattern?
Two stable branches are simpler as an if/else. Strategy pays off when variants grow or change.
5. In Java, when is a lambda a good replacement for a concrete strategy class?
Any interface with one abstract method can take a lambda. A class is better when the strategy has state, several methods, or needs its own tests and docs.
6. Adding a BusRoute class without editing Navigator or the other routes is an example of which principle?
The system is extended with a new class without modifying existing, tested code: the open/closed principle. (Navigator depending on the RouteStrategy interface is dependency inversion, which is what makes it possible.)
Score 60% or more and the lesson is marked complete.