Polski

Article · Strategy · SOLID

Strategy: interchangeable algorithms instead of an if-else ladder

The Strategy pattern through courier assignment in a pierogi place: a family of interchangeable algorithms behind one interface, swapped at runtime. Code in C#, TypeScript, Java, Go and Python.

By · · 13 min read

Halina's pierogi place delivers orders, and a dozen lines of code decide which courier rides off with the hot potato-and-cheese pierogi. In the morning the nearest courier wins; on a Friday evening it is the least busy one. Strategy lets you keep each of these algorithms in its own class and swap them without touching the code that uses them.

1994
the GoF book is published – Gamma, Helm, Johnson, Vlissides
11
behavioral patterns in the GoF catalog – Strategy opens this series
0
changes in the context – when a new algorithm is added

The problem: an algorithm welded into the code

The first version of the dispatcher was simple: one mode parameter and a few branches. A year later it looked like this:

assign-courier.ts
function assignCourier(couriers: Courier[], mode: string, raining: boolean): Courier | undefined {
  if (mode === 'nearest') {
    return couriers.reduce((a, b) => (b.distanceKm < a.distanceKm ? b : a));
  } else if (mode === 'least-busy') {
    return [...couriers].sort((a, b) => a.activeOrders - b.activeOrders)[0];
  } else if (mode === 'rush') {
    // copy of 'least-busy' + "skip couriers with 4+ orders"
    const free = couriers.filter((c) => c.activeOrders < 4);
    return [...free].sort((a, b) => a.activeOrders - b.activeOrders)[0];
  }
  if (raining) {
    // nobody remembers why this is here
    return couriers.find((c) => c.vehicle === 'car');
  }
  throw new Error(`Unknown mode: ${mode}`);
}

Every rule change means editing the same function. Branches copy pieces of each other, the weather condition dangles outside the rest of the logic, and a test for "rush mode" has to walk through every if. You also cannot add an algorithm from the outside – say, in a loyalty module for regular customers – without modifying this file. It is a textbook violation of the Open/Closed Principle from SOLID.

The solution: pull the algorithm behind an interface

The idea is short: every way of choosing a courier becomes a separate object with the same pick(order, couriers) method. The dispatcher (the context) holds a reference to "some strategy" and delegates the decision to it. Who picks the concrete strategy and when – configuration, a schedule, a feature flag – is a separate concern.

Diagram: The structure of the Strategy pattern
RoleIn the exampleResponsibility
StrategyAssignmentStrategythe common interface of all algorithms
Concrete strategyNearestCourier, LeastBusyCourierone variant of the algorithm, unaware of the others
ContextDispatcherholds a strategy and delegates work to it
Clientconfiguration, schedulerchooses a strategy and hands it to the context

The interesting part happens at runtime: the strategy can be swapped on the fly and the dispatcher does not even notice.

Diagram: Swapping the strategy on a Friday evening

Implementation in five languages

The example is deliberately small: two strategies, a context and a short demo of swapping. Notice that in TypeScript, Go and Python a strategy can simply be a function – the pattern does not require classes, only a shared signature.

Strategy – courier assignment

Dispatcher.cs
var couriers = new List<Courier> { new("Ania", 1.2, 3), new("Bartek", 2.5, 0) };
var dispatcher = new Dispatcher(new NearestCourier());
Console.WriteLine(dispatcher.Assign(new Order(1, "Długa 5"), couriers));  // -> Ania
dispatcher.Use(new LeastBusyCourier());                                   // Friday rush
Console.WriteLine(dispatcher.Assign(new Order(2, "Krótka 7"), couriers)); // -> Bartek

public sealed record Courier(string Name, double DistanceKm, int ActiveOrders);
public sealed record Order(int Id, string Address);

public interface IAssignmentStrategy
{
    Courier? Pick(Order order, IReadOnlyList<Courier> couriers);
}

public sealed class NearestCourier : IAssignmentStrategy
{
    public Courier? Pick(Order order, IReadOnlyList<Courier> couriers) =>
        couriers.MinBy(c => c.DistanceKm);
}

public sealed class LeastBusyCourier : IAssignmentStrategy
{
    public Courier? Pick(Order order, IReadOnlyList<Courier> couriers) =>
        couriers.OrderBy(c => c.ActiveOrders).ThenBy(c => c.DistanceKm).FirstOrDefault();
}

public sealed class Dispatcher(IAssignmentStrategy strategy)
{
    private IAssignmentStrategy _strategy = strategy;

    // The algorithm can be swapped at runtime without touching Dispatcher.
    public void Use(IAssignmentStrategy strategy) => _strategy = strategy;

    public string Assign(Order order, IReadOnlyList<Courier> couriers) =>
        _strategy.Pick(order, couriers) is { } courier
            ? $"Order #{order.Id} -> {courier.Name}"
            : $"Order #{order.Id} waits for a free courier";
}
dispatcher.ts
interface Courier { name: string; distanceKm: number; activeOrders: number }
interface Order { id: number; address: string }

// In TypeScript a strategy can simply be a function type.
type AssignmentStrategy = (order: Order, couriers: readonly Courier[]) => Courier | undefined;

const nearest: AssignmentStrategy = (_order, couriers) =>
  couriers.reduce<Courier | undefined>((best, c) => (!best || c.distanceKm < best.distanceKm ? c : best), undefined);

const leastBusy: AssignmentStrategy = (_order, couriers) =>
  [...couriers].sort((a, b) => a.activeOrders - b.activeOrders || a.distanceKm - b.distanceKm)[0];

class Dispatcher {
  constructor(private strategy: AssignmentStrategy) {}

  use(strategy: AssignmentStrategy): void {
    this.strategy = strategy;
  }

  assign(order: Order, couriers: readonly Courier[]): string {
    const courier = this.strategy(order, couriers);
    return courier ? `Order #${order.id} -> ${courier.name}` : `Order #${order.id} waits for a free courier`;
  }
}

const couriers: Courier[] = [
  { name: 'Ania', distanceKm: 1.2, activeOrders: 3 },
  { name: 'Bartek', distanceKm: 2.5, activeOrders: 0 },
];
const dispatcher = new Dispatcher(nearest);
console.log(dispatcher.assign({ id: 1, address: 'Długa 5' }, couriers)); // -> Ania
dispatcher.use(leastBusy); // Friday rush
console.log(dispatcher.assign({ id: 2, address: 'Krótka 7' }, couriers)); // -> Bartek
Dispatcher.java
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

record Courier(String name, double distanceKm, int activeOrders) {}
record Order(int id, String address) {}

@FunctionalInterface
interface AssignmentStrategy {
    Optional<Courier> pick(Order order, List<Courier> couriers);
}

final class NearestCourier implements AssignmentStrategy {
    public Optional<Courier> pick(Order order, List<Courier> couriers) {
        return couriers.stream().min(Comparator.comparingDouble(Courier::distanceKm));
    }
}

final class LeastBusyCourier implements AssignmentStrategy {
    private static final Comparator<Courier> BY_LOAD =
        Comparator.comparingInt(Courier::activeOrders).thenComparingDouble(Courier::distanceKm);

    public Optional<Courier> pick(Order order, List<Courier> couriers) {
        return couriers.stream().min(BY_LOAD);
    }
}

public class Dispatcher {
    private AssignmentStrategy strategy;

    public Dispatcher(AssignmentStrategy strategy) { this.strategy = strategy; }

    public void use(AssignmentStrategy strategy) { this.strategy = strategy; }

    public String assign(Order order, List<Courier> couriers) {
        return strategy.pick(order, couriers)
            .map(c -> "Order #" + order.id() + " -> " + c.name())
            .orElse("Order #" + order.id() + " waits for a free courier");
    }

    public static void main(String[] args) {
        var couriers = List.of(new Courier("Ania", 1.2, 3), new Courier("Bartek", 2.5, 0));
        var dispatcher = new Dispatcher(new NearestCourier());
        System.out.println(dispatcher.assign(new Order(1, "Długa 5"), couriers));  // -> Ania
        dispatcher.use(new LeastBusyCourier());                                    // Friday rush
        System.out.println(dispatcher.assign(new Order(2, "Krótka 7"), couriers)); // -> Bartek
    }
}
dispatcher.go
package main

import (
	"cmp"
	"fmt"
	"slices"
)

type Courier struct {
	Name         string
	DistanceKm   float64
	ActiveOrders int
}

type Order struct{ ID int }

// AssignmentStrategy picks a courier; ok is false when nobody is available.
type AssignmentStrategy interface {
	Pick(o Order, couriers []Courier) (c Courier, ok bool)
}

// StrategyFunc lets plain functions act as strategies (like http.HandlerFunc).
type StrategyFunc func(Order, []Courier) (Courier, bool)

func (f StrategyFunc) Pick(o Order, cs []Courier) (Courier, bool) { return f(o, cs) }

func minBy(cs []Courier, less func(a, b Courier) int) (Courier, bool) {
	if len(cs) == 0 {
		return Courier{}, false
	}
	return slices.MinFunc(cs, less), true
}

var Nearest = StrategyFunc(func(_ Order, cs []Courier) (Courier, bool) {
	return minBy(cs, func(a, b Courier) int { return cmp.Compare(a.DistanceKm, b.DistanceKm) })
})

var LeastBusy = StrategyFunc(func(_ Order, cs []Courier) (Courier, bool) {
	return minBy(cs, func(a, b Courier) int {
		return cmp.Or(cmp.Compare(a.ActiveOrders, b.ActiveOrders), cmp.Compare(a.DistanceKm, b.DistanceKm))
	})
})

type Dispatcher struct{ Strategy AssignmentStrategy }

func (d *Dispatcher) Assign(o Order, cs []Courier) string {
	if c, ok := d.Strategy.Pick(o, cs); ok {
		return fmt.Sprintf("Order #%d -> %s", o.ID, c.Name)
	}
	return fmt.Sprintf("Order #%d waits for a free courier", o.ID)
}

func main() {
	cs := []Courier{{"Ania", 1.2, 3}, {"Bartek", 2.5, 0}}
	d := &Dispatcher{Strategy: Nearest}
	fmt.Println(d.Assign(Order{1}, cs)) // -> Ania
	d.Strategy = LeastBusy             // Friday rush
	fmt.Println(d.Assign(Order{2}, cs)) // -> Bartek
}
dispatcher.py
from dataclasses import dataclass
from typing import Protocol, Sequence


@dataclass(frozen=True)
class Courier:
    name: str
    distance_km: float
    active_orders: int


@dataclass(frozen=True)
class Order:
    id: int
    address: str


class AssignmentStrategy(Protocol):
    def __call__(self, order: Order, couriers: Sequence[Courier]) -> Courier | None: ...


def nearest(order: Order, couriers: Sequence[Courier]) -> Courier | None:
    return min(couriers, key=lambda c: c.distance_km, default=None)


def least_busy(order: Order, couriers: Sequence[Courier]) -> Courier | None:
    return min(couriers, key=lambda c: (c.active_orders, c.distance_km), default=None)


class Dispatcher:
    def __init__(self, strategy: AssignmentStrategy) -> None:
        self.strategy = strategy  # swap it any time, e.g. during the Friday rush

    def assign(self, order: Order, couriers: Sequence[Courier]) -> str:
        courier = self.strategy(order, couriers)
        if courier is None:
            return f"Order #{order.id} waits for a free courier"
        return f"Order #{order.id} -> {courier.name}"


couriers = [Courier("Ania", 1.2, 3), Courier("Bartek", 2.5, 0)]
dispatcher = Dispatcher(nearest)
print(dispatcher.assign(Order(1, "Długa 5"), couriers))   # -> Ania
dispatcher.strategy = least_busy
print(dispatcher.assign(Order(2, "Krótka 7"), couriers))  # -> Bartek

Who chooses the strategy?

The pattern moves the "how" decision into the strategy, but the "which one" decision still has to be made somewhere. You will usually find it in one of three places:

  1. Configuration at startup – the DI container registers one implementation of the interface (services.AddSingleton<IAssignmentStrategy, LeastBusyCourier>()), and a change only needs a different configuration entry.
  2. A strategy registry – a name → strategy dictionary filled at startup. Halina's admin panel shows the list of keys and the dispatcher fetches a strategy by name. A single switch in a factory is fine – the problem was a switch scattered across business logic.
  3. A runtime rule – a scheduler, a feature flag or an A/B test swaps the strategy on the fly, just like in the sequence diagram above.

Stateless strategies (like both in the example) can be safely shared between threads and registered as singletons. A stateful strategy – for example round-robin rotation of couriers, which remembers the last one picked – needs some thought about concurrency, or a separate instance per context.

Step by step

  1. Step 1 Find the axis of change – What varies independently of the rest? Here: the courier selection rule, not the way an order is saved.
  2. Step 2 Define the interface – One method with the data every variant needs (order, couriers). Do not pass the whole context "just in case".
  3. Step 3 Move branches into classes – Each if becomes a concrete strategy. Duplicated code comes to light – and usually disappears.
  4. Step 4 Inject the strategy – The context receives it through a constructor or setter. A DI container or a factory picks the variant.
  5. Step 5 Test separately – You test each strategy without the dispatcher, and the dispatcher with a fake strategy.

What does it look like in numbers? Below is an illustrative simulation of one Friday evening: as orders pile up, the "nearest" strategy overloads a few couriers, while "least busy" spreads the work more evenly.

Average delivery time on a Friday evening – Illustrative data – made-up values, not a measurement from a real pierogi place.
Nearest courierLeast busy
5 pm24 min27 min
6 pm31 min29 min
7 pm42 min32 min
8 pm47 min34 min
9 pm33 min30 min

When to use it and when not to

Pros

  • a new algorithm without modifying the context (Open/Closed Principle)
  • each variant tested in isolation
  • behaviour swapped at runtime (configuration, feature flags, A/B tests)
  • composition over inheritance – no explosion of context subclasses

Cons

  • more types and files when there are just two simple variants
  • the client has to understand the differences between strategies to pick the right one
  • the shared interface can be a compromise: one strategy needs data the others ignore

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

— Gamma, Helm, Johnson, Vlissides · Design Patterns (1994)
  • State has an identical class diagram but a different intent: states switch the context themselves, while a strategy is chosen from the outside.
  • Template Method varies part of an algorithm through inheritance; Strategy replaces the whole algorithm through composition.
  • Decorator changes the "skin" of an object by adding behaviour around it; Strategy changes its "guts".
  • Factory Method often decides which strategy to create based on configuration.
  • Command also wraps behaviour in an object, but it represents a request (what to do), not a way (how to do it).

In practice: where you already use Strategy

PlatformExampleWhat the strategy is
.NETnew Dictionary<string, int>(StringComparer.OrdinalIgnoreCase)IEqualityComparer<T> decides how keys are compared
.NETlist.Sort(IComparer<T>)the element comparison algorithm
Java / SpringList.sort(Comparator), PasswordEncodercomparison, password hashing (BCryptPasswordEncoder, Argon2PasswordEncoder)
Node.jsPassport.js: passport.use(new LocalStrategy(...))the authentication method – the library literally calls them strategies
Goslices.SortFunc(s, cmp), sort.Slice(s, less)the comparison function passed to the sorting algorithm
Pythonsorted(items, key=...), json.dumps(obj, default=...)the key function, how unknown types are serialised

The pattern is so common that we often do not notice it: every function that accepts a "comparison function" or a "policy" is a Strategy in miniature.

Test yourself

Question: The dispatcher checks if (strategy is LeastBusyCourier) and then additionally skips couriers on bikes. What is wrong?

  • Nothing – it is a valid extension of the pattern
  • The context depends on a concrete strategy; the rule belongs in a strategy or a new variant
  • Strategy should be replaced with subclasses of Dispatcher
Interview question: how does Strategy differ from State if the diagrams are identical?

The difference is the intent and who switches the object. In Strategy the client (configuration, the user) chooses the algorithm, and strategies usually do not know about each other. In State the state objects represent stages of the context's life cycle and themselves decide on the transition to the next state (e.g. Paid → InKitchen). A good answer also mentions that a strategy is usually stateless and easy to share, while a state often holds data of its stage.

Exercise

Implement your own family of discount strategies for a shopping cart – percentage, threshold and "best of" – and check it with tests:

Challenge: Discount strategy