bigonotes
CS ConceptsDesign Patterns

Strategy Pattern

Replace if/else chains of algorithms with interchangeable strategy objects that a context can swap at runtime.

7 min readLast updated

A navigation app can route you by car, on foot or by transit. An online store can ship a parcel by standard post, by express courier, or hold it for pickup. When one task has several interchangeable algorithms, putting them all in one if/else makes a giant class that changes every time a new option appears.

Strategy moves each algorithm into its own class behind a shared interface, and lets the main object swap them at runtime. Of all the patterns, it's the one LLD interviews lean on most.

Intent#

The original definition names the three parts of the idea (a family, encapsulation, and swapping):

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

Analogy: route options in a maps app: fastest, shortest, avoid tolls. The app is the same; you pick how it computes the route.

The problem: the if/elif monster#

The naive version puts every algorithm in one method:

class Navigator:
    def calculate_route(self, start: str, end: str, mode: str) -> str:
        if mode == "DRIVING":
            # ... 50 lines of traffic calculations ...
            return f"Driving route from {start} to {end} via Highway 1."
        elif mode == "WALKING":
            # ... 50 lines of sidewalk and trail logic ...
            return f"Walking route from {start} to {end} via Park Trail."
        elif mode == "TRANSIT":
            # ... 50 lines of bus schedule lookups ...
            return f"Transit route from {start} to {end} via Bus 42."
        else:
            raise ValueError("Unsupported routing mode")

It works for three modes, but it scales badly:

  1. Violates Open/Closed: adding BICYCLE means editing Navigator.
  2. God class: real routing algorithms are hundreds of lines each; this file becomes enormous.
  3. Merge conflicts: three developers working on three modes all edit the same file.
  4. Hard to test: you can't test walking logic in isolation.

Structure#

The context holds one strategy at a time and delegates to it. Swapping the algorithm means pointing that one reference somewhere else.

Strategy: a Navigator context holds one RouteStrategy reference that can point at Driving, Walking or Transit

Three roles make this work:

Participant Role
Strategy The interface every algorithm implements (RouteStrategy)
Concrete strategies One class per algorithm (DrivingStrategy, WalkingStrategy)
Context Holds a strategy reference, delegates the work to it, and allows swapping (Navigator)

Example 1: navigation#

Here's the navigator from above with each routing mode moved into its own class:

from abc import ABC, abstractmethod


class RouteStrategy(ABC):
    @abstractmethod
    def build_route(self, start: str, end: str) -> str: ...


class DrivingStrategy(RouteStrategy):
    def build_route(self, start: str, end: str) -> str:
        return f"Driving route from {start} to {end} via Highway 1."


class WalkingStrategy(RouteStrategy):
    def build_route(self, start: str, end: str) -> str:
        return f"Walking route from {start} to {end} via Park Trail."


class TransitStrategy(RouteStrategy):
    def build_route(self, start: str, end: str) -> str:
        return f"Transit route from {start} to {end} via Bus 42."


class Navigator:
    def __init__(self, strategy: RouteStrategy):  # inject a default
        self._strategy = strategy

    # Swap at runtime
    def set_strategy(self, strategy: RouteStrategy) -> None:
        self._strategy = strategy

    def calculate_route(self, start: str, end: str) -> str:
        return self._strategy.build_route(start, end)  # delegate blindly


navigator = Navigator(DrivingStrategy())
print(navigator.calculate_route("Home", "Office"))  # Driving route ...

# Traffic is bad; the user taps "Walk"
navigator.set_strategy(WalkingStrategy())
print(navigator.calculate_route("Home", "Office"))  # Walking route ...

Adding BicycleStrategy is a new class; Navigator doesn't change. Each strategy has one job and can be unit-tested alone.

Example 2: shipping options#

Shipping is another classic case. A strategy can hold its own data and expose several methods, as long as they share one interface. Here the order is the context and each delivery option is a strategy.

from abc import ABC, abstractmethod


class ShippingStrategy(ABC):
    @abstractmethod
    def accepts(self, weight_kg: float) -> bool: ...

    @abstractmethod
    def cost(self, weight_kg: float) -> float: ...

    @abstractmethod
    def days(self) -> int: ...


class StandardPost(ShippingStrategy):
    def __init__(self, per_kg: float = 1.20):
        self._per_kg = per_kg

    def accepts(self, weight_kg: float) -> bool:
        return weight_kg <= 30

    def cost(self, weight_kg: float) -> float:
        return round(4.00 + weight_kg * self._per_kg, 2)

    def days(self) -> int:
        return 5


class ExpressCourier(ShippingStrategy):
    def __init__(self, base: float = 12.00, max_kg: float = 20):
        self._base = base
        self._max_kg = max_kg

    def accepts(self, weight_kg: float) -> bool:
        return weight_kg <= self._max_kg

    def cost(self, weight_kg: float) -> float:
        return round(self._base + weight_kg * 2.50, 2)

    def days(self) -> int:
        return 1


class StorePickup(ShippingStrategy):
    def __init__(self, store: str):
        self._store = store

    def accepts(self, weight_kg: float) -> bool:
        return True  # any size can wait at the counter

    def cost(self, weight_kg: float) -> float:
        return 0.0

    def days(self) -> int:
        return 2


# Context
class Order:
    def __init__(self):
        self._weights: list[float] = []
        self._shipping: ShippingStrategy | None = None

    def add_item(self, weight_kg: float) -> None:
        self._weights.append(weight_kg)

    def set_shipping(self, strategy: ShippingStrategy) -> None:
        self._shipping = strategy

    def quote(self) -> str:
        if self._shipping is None:
            raise RuntimeError("Choose a shipping option first")
        total = sum(self._weights)
        # The order doesn't know HOW any option prices a parcel
        if not self._shipping.accepts(total):
            return f"Too heavy for this option ({total} kg)"
        cost = self._shipping.cost(total)
        return f"${cost:.2f}, {self._shipping.days()}-day delivery"


order = Order()
order.add_item(2.5)
order.add_item(0.5)

order.set_shipping(StandardPost())
print(order.quote())   # $7.60, 5-day delivery

# Change of mind
order.set_shipping(ExpressCourier())
print(order.quote())   # $19.50, 1-day delivery

order.set_shipping(StorePickup("Main St"))
print(order.quote())   # $0.00, 2-day delivery

The same structure fits any "pick one behavior" problem. In a game, a MapStrategy (desert, ice, jungle) could supply terrain rendering, physics rules and enemy spawning, and a power-up could swap the map mid-game with game.switch_map(IceMapStrategy()).

Example 3: functions as strategies#

Both examples so far used a class per algorithm. If the strategy has only one method, you don't need that. Any callable (a lambda or a plain function) is a strategy:

from typing import Callable

Discount = Callable[[float], float]


class PriceCalculator:
    def __init__(self):
        self._discount: Discount = lambda p: p  # default: no discount

    def set_discount(self, discount: Discount) -> None:
        self._discount = discount

    def calculate(self, price: float) -> float:
        return self._discount(price)


def tiered(p: float) -> float:
    if p > 100:
        return p * 0.7
    if p > 50:
        return p * 0.9
    return p


calc = PriceCalculator()
calc.set_discount(lambda p: p * 0.9)  # regular customer: 10% off
calc.set_discount(lambda p: p * 0.8)  # premium: 20% off
calc.set_discount(tiered)             # a named function works too
print(calc.calculate(200))            # 140.0

Template#

Strip the examples down and this is the shape to remember:

from abc import ABC, abstractmethod


class Strategy(ABC):
    @abstractmethod
    def execute(self) -> None: ...


class ConcreteStrategyA(Strategy):
    def execute(self) -> None:
        print("A")


class ConcreteStrategyB(Strategy):
    def execute(self) -> None:
        print("B")


class Context:
    def __init__(self, strategy: Strategy):
        self._strategy = strategy

    def set_strategy(self, strategy: Strategy) -> None:
        self._strategy = strategy

    def perform_operation(self) -> None:
        self._strategy.execute()


ctx = Context(ConcreteStrategyA())
ctx.perform_operation()
ctx.set_strategy(ConcreteStrategyB())
ctx.perform_operation()

Real-world examples#

You've likely used Strategy already:

  • The key= function passed to sorted(), min() and max(): the comparison rule is the strategy.
  • json.dumps(obj, default=...): you supply the algorithm for encoding unknown types.
  • logging.Formatter subclasses: the same handler, different formatting algorithms.
  • Django's pluggable authentication backends.
  • Business: pricing and discount rules, game AI (aggressive, defensive), export formats (PDF, Excel, CSV), compression algorithms, validation rules.

When to use it#

Strategy fits when:

  • There are several ways to do the same task, and you pick one at runtime (often the user picks).
  • A class has a growing if/elif or match over algorithm types.
  • You want to isolate algorithm details and test each one alone.
  • Algorithms should vary independently from the code that uses them.

When not to use it#

Skip it when:

  • There are only two simple, stable branches. An if is clearer.
  • The algorithm never changes.
  • The algorithms need very different inputs, which forces a bloated shared interface.

Pitfalls#

Watch for these trade-offs:

  • Clients must know the strategies to choose one. Pair Strategy with a factory when the choice comes from config or user input.
  • Class count grows with the number of algorithms (plain functions help).
  • Data passing. Context and strategy must agree on what data flows between them; passing the whole context couples them.
  • Null strategy. Give the context a sensible default (as PriceCalculator does) or fail loudly.

Strategy vs similar patterns#

Several patterns look like Strategy at first glance:

Pattern Difference
State Same structure, different intent: the client picks a strategy; a state object changes itself as internal state changes
Template Method Replaces some steps via inheritance; Strategy replaces the whole algorithm via composition
Command Wraps a request (what to do, possibly undoable); Strategy is how to do one task
Bridge Two hierarchies vary; in Strategy only the algorithm does

Strategy is "composition over inheritance": the object is composed with a behavior rather than inheriting it.

Key takeaways#

  • Strategy = one interface, many interchangeable algorithm classes, and a context that delegates to one of them.
  • It replaces conditionals with polymorphism and satisfies Open/Closed.
  • Strategies can be swapped at runtime via a setter or chosen via constructor injection.
  • With single-method interfaces, lambdas or plain functions are strategies.
  • Strategy and State look alike; the difference is who chooses the behavior.
Revision notes · 2 min

Core idea#

Strategy moves each interchangeable algorithm into its own class behind a shared interface. A context holds one strategy, delegates to it, and can swap it at runtime.

Key points#

  • Participants: the strategy interface, one concrete strategy per algorithm, and the context.
  • It replaces an if/elif chain with polymorphism and satisfies Open/Closed.
  • A new algorithm is a new class. The context does not change.
  • Each strategy has one job, so you can unit-test it alone.
  • Choose a strategy with constructor injection, or swap it with a setter.
  • With a single-method interface, a lambda or plain function is a strategy.
  • Python examples: the key= function for sorted(), json.dumps(default=...), logging.Formatter subclasses.

Use it or skip it#

Use Strategy when Skip it when
Several ways exist to do one task, picked at runtime Two simple, stable branches exist
An if/elif over algorithm types keeps growing The algorithm never changes
You want to test each algorithm alone Algorithms need very different inputs

Strategy vs similar patterns#

Pattern Difference
State Same structure; the client picks a strategy, but a state changes itself
Template Method Replaces some steps via inheritance; Strategy replaces the whole algorithm via composition
Command Wraps a request; Strategy is how to do one task
Bridge Two hierarchies vary; in Strategy only the algorithm varies

Pitfalls#

  • Clients must know the strategies to choose one. Pair Strategy with a factory when config or user input decides.
  • Class count grows with the number of algorithms. Plain functions help.
  • Passing the whole context to the strategy couples them.
  • A missing strategy breaks the context. Give it a sensible default, or fail loudly.

Say it in an interview#

  • "One interface, many interchangeable algorithms, and a context that delegates to one of them."
  • "Strategy is composition over inheritance. The object is composed with a behavior."
  • "Strategy and State look alike. The difference is who chooses the behavior."

Found a mistake? Email ask@bigonotes.com