Patterns for behaviour · Chapter 15

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.

BeginnerInterview priority: High40 min
On this page
  1. The problem: one method that does everything
  2. The idea: one interface, one class per algorithm
  3. Build it step by step
  4. But someone still has to choose
  5. Strategies with no class at all
  6. Strategy, State, Template Method: how they differ
  7. When not to use it
  8. In the interview
  9. Quiz

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

  1. 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

  1. 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.
  2. 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:

RoleIn this exampleResponsibility
Strategy (interface)RouteStrategyDeclares the one operation all algorithms share: build(a, b)
Concrete strategiesCarRoute, BikeRoute, WalkRouteEach implements the algorithm its own way
ContextNavigatorHolds 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);

Adding a new mode touches nothing old

Adding a bus route: one new class, nothing edited

  1. 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()));

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

A 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

  1. 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.

StrategyStateTemplate Method
What variesThe algorithm for one jobBehaviour that depends on the object's current stateSome steps inside a fixed algorithm
Who choosesThe client, from outsideThe object itself, as it changes stateFixed by the subclass you instantiate
Do the variants know each other?No, they are independentOften: a state may choose the next state (or the context decides the transitions)No
MechanismComposition: context has a strategyComposition: context has a current stateInheritance: subclass overrides steps
ExamplePay by card, PayPal or UPIVending machine: Idle → HasCoin → DispensingData 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

Your turn: checkout discounts

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.

Strategy on one page
  • 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.
Your turn: the requirement changes

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.

Interactive labPractise it: ship new travel modes and see what breaksOpens in the ByteAtlas lab. Your progress is saved in this browser.
Check what stuck

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?

2. What is the main difference between Strategy and State?

3. After introducing Strategy, the code still has if (mode.equals("car")) return new CarRoute(); …. What is the best way to handle that?

4. Which situation is the weakest case for the Strategy pattern?

5. In Java, when is a lambda a good replacement for a concrete strategy class?

6. Adding a BusRoute class without editing Navigator or the other routes is an example of which principle?

Score 60% or more and the lesson is marked complete.

Passing the quiz also marks it complete. Progress is saved in this browser only.