# Strategy PatternOne 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**.

{{< lesson-video youtube="hkq8-qyyOfI" title="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?":

```mermaid {alt="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." caption="One job, several interchangeable ways to do it, picked from outside."}
flowchart TD
  R(["route(home, airport)"]) --> Q{"What did the<br/>user choose?"}
  Q -->|fastest| F["highway + toll<br/>25 min"]
  Q -->|avoid tolls| A["back roads<br/>34 min"]
  Q -->|walking| W["paths and stairs<br/>2 h 10"]
  class R c6
  class F c4
  class A c1
  class W c2
```

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:

```java
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.

```mermaid {alt="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." caption="The context contains every algorithm and picks one with a switch."}
flowchart TD
  subgraph NAV["Navigator: knows every algorithm"]
    direction TB
    S{"switch (mode)"}
    S -->|FASTEST| F["fastestRoute()<br/>40 lines"]
    S -->|AVOID_TOLLS| A["noTollRoute()<br/>35 lines"]
    S -->|WALKING| W["walkingRoute()<br/>30 lines"]
  end
  class S bad
  class F c4
  class A c1
  class W c2
```

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:

```java
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.

```mermaid {alt="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." caption="One new algorithm, five edits in one class."}
flowchart LR
  C["+ CYCLING"] --> E["enum Mode"]
  C --> R["route() switch"]
  C --> T["eta() switch"]
  C --> H["new private helper"]
  C --> N["NavigatorTest"]
  T -.->|"forgot it?"| X["IllegalArgumentException<br/>at run time"]
  class C c5
  class E,R,T,H,N warn
  class X bad
```

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](/code-smells/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.

```mermaid {alt="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." caption="The drill keeps the job; the bit supplies the how."}
flowchart LR
  subgraph TOOL["The drill"]
    direction TB
    D["drill: it turns"] --> CH["chuck: every bit fits"]
    CH --> B["bit for wood,<br/>metal, concrete"]
    Y["you pick the bit"] -.-> B
  end
  subgraph CODE["The code"]
    direction TB
    N["Navigator<br/>(context)"] --> I["RouteStrategy<br/>(interface)"]
    I --> S["Fastest, AvoidTolls,<br/>Walking"]
    CL["client chooses"] -.-> S
  end
  TOOL ~~~ CODE
  class D,N c6
  class CH,I hl
  class B,S c1
```

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`:

```java
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:

```java
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.

```java
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.

```java
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
```

```mermaid {alt="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." caption="The client swaps the strategy; the navigator just delegates."}
sequenceDiagram
  participant C as Client
  participant N as Navigator
  participant F as Fastest
  participant A as AvoidTolls
  C->>N: new Navigator(Fastest)
  C->>N: route(home, airport)
  N->>F: plan(...)
  F-->>C: highway, 25 min
  Note over C: user taps "avoid tolls"
  C->>N: setStrategy(AvoidTolls)
  C->>N: route(home, airport)
  N->>A: plan(...)
  A-->>C: back roads, 34 min
```

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.

```java
class Cycling implements RouteStrategy {
    public Route plan(Point from, Point to) { /* bike lanes, no highways */ }
}
```

```mermaid {alt="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." caption="Strategy: a context, one interface, interchangeable implementations, and a client that chooses."}
classDiagram
  class Client
  class Navigator {
    -RouteStrategy strategy
    +setStrategy(RouteStrategy s)
    +route(Point from, Point to) Route
  }
  class RouteStrategy {
    <<interface>>
    +plan(Point from, Point to) Route
  }
  class Fastest
  class AvoidTolls
  class Walking
  class Cycling
  Client ..> Navigator : hands in a strategy
  Navigator o--> RouteStrategy
  RouteStrategy <|.. Fastest
  RouteStrategy <|.. AvoidTolls
  RouteStrategy <|.. Walking
  RouteStrategy <|.. Cycling
  note for Cycling "added later: Navigator unchanged"
```

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](/fundamentals/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();`).

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

## 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`:

```java
@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:

```java
List<Order> orders = loadOrders();
orders.sort(Comparator.comparing(Order::total));              // cheapest first
orders.sort(Comparator.comparing(Order::placedAt).reversed()); // newest first
```

```mermaid {alt="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." caption="The sorting algorithm stays; the rule for comparing is what you swap."}
flowchart TD
  S["List.sort(comparator)<br/>the algorithm stays"] --> Q{"which comparator?"}
  Q -->|"by total"| A["cheapest first"]
  Q -->|"by placedAt, reversed"| B["newest first"]
  class S c6
  class Q hl
  class A c4
  class B c1
```

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.

```java
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**:

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

```mermaid {alt="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." caption="The choice happens once, at the edge; the checkout just delegates."}
sequenceDiagram
  actor U as Customer
  participant F as Client (form handler)
  participant K as Checkout
  participant P as PaymentMethod
  U->>F: chooses "card"
  Note over F: the one switch, at the edge
  F->>P: new CardPayment(cardNumber)
  F->>K: complete(cart, chosen)
  K->>P: pay(cart.total())
  P-->>K: Receipt
  K-->>U: Receipt
```

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](/patterns/state-pattern/), this might look familiar. The
class diagrams are identical: a context, an interface, and several implementations. The
difference is **who changes it**.

```mermaid {alt="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." caption="Same structure, opposite direction of control."}
flowchart LR
  subgraph STRAT["Strategy: chosen from outside"]
    direction TB
    CL["Client"] -->|"chooses once"| NAV["Navigator"]
    NAV -->|"delegates to"| AT["AvoidTolls"]
  end
  subgraph STATE["State: changed from inside"]
    direction TB
    S1["NoCoinState"] -->|"insertCoin()"| S2["HasCoinState"]
    S2 -->|"last snack sold"| S3["SoldOutState"]
  end
  STRAT ~~~ STATE
  class NAV c6
  class AT c1
  class S1 nocoin
  class S2 hascoin
  class S3 soldout
```

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

| | **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](/patterns/template-method-pattern/)** 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.

```mermaid {alt="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." caption="When Strategy pays for itself, and what shape to give it."}
flowchart TD
  Q1{"More than one way<br/>to do the job?"}
  Q1 -->|no| K1["No pattern needed"]
  Q1 -->|yes| Q2{"Just two tiny variants<br/>that never change?"}
  Q2 -->|yes| K2["A plain if"]
  Q2 -->|no| Q3{"One-line algorithms?"}
  Q3 -->|yes| L["Strategy as lambdas"]
  Q3 -->|"no: state, several methods,<br/>a name"| U["Strategy classes"]
  class L,U good
  class K1,K2 muted
```

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

```mermaid {alt="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." caption="Keep the what. Swap the how."}
flowchart LR
  A["switch (mode)<br/>in the context"] --> B["one interface"]
  B --> C["one class or lambda<br/>per algorithm"]
  C --> D["client chooses,<br/>context delegates"]
  class A bad
  class B hl
  class C c1
  class D good
```

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

```java
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);
    }
}
```
