AlgoViz

Strategy pattern

medium 55 min

Define a family of interchangeable algorithms behind one interface.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:30

Strategy

1:02Reel

Strategy pattern in one picture
Strategy pattern in one picture

More reels

One idea each, a minute or less.

Play all in Bytesized Learning

State vs strategy

0:33Reel

Strategy vs template method

0:34Reel

Theory

Read or listen first. About 2 min.

What it is

Strategy is a behavioral design pattern. It takes an algorithm out of the class that uses it and puts it behind an interface. The class, now called the context, holds a reference to one strategy and delegates to it.

It is composition used to vary behaviour. Instead of a subclass PayPalCart there is one ShoppingCart that has a payment. Two choices, payment and discount, stay two slots and do not multiply into subclasses.

In languages with first-class functions a strategy is often just a function that is passed in: the key of a sort, a comparator, a callback that decides.

Why it exists

Conditions that pick an algorithm spread. The same branch appears in pay, in refund and in label, and the copies drift apart. With an object per way, all answers about one way stand together.

It separates two reasons to change: the job (what a checkout does, in which order) and the ways (how money moves). Different people change them at different times.

It makes tests small. The context is tested with a fake strategy, each strategy without a context.

It gives run-time choice: by user, by data size, by configuration, by experiment.

A short history

  1. 1994

    The book Design Patterns lists Strategy among its behavioral patterns.

  2. 2005

    Python 2.4 (2.4.1 on 30 March 2005 in its What's New page) lets sort take a key function: a strategy as a plain function.

  3. 2014

    Java 8 brings lambda expressions (JEP 126). A Comparator can now be written in one line.

  4. 2019

    Python 3.8 adds Protocol (PEP 544): a strategy interface without a common base class.

Words to know

Context
The object that has the job and holds a strategy.
Strategy
The interface of the family, and also any member of it.
Concrete strategy
One algorithm as a class or function.
Client
Whoever chooses a strategy and hands it over.
Delegation
Answering a call by passing it to another object.
Injection
Giving an object what it needs from outside, usually in the constructor.
Registry
A map from stable names to constructors of strategies.
Null object
A strategy that does nothing on purpose, such as no discount.
Policy
Another word for strategy, common when it is a type parameter.
Contract test
One test that every member of the family must pass.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 3

Define interface. One contract for the algorithm family

Understand it

Start here

One sled, many runners

A program often has one job and several ways to do it: pay by card or by wallet, sort a short list or a long one, drive the fast road or the pretty one. The pattern on this page keeps the job in one place and makes each way a part that you can take off and put on.

Noor's sled
SNOW!

Somebody still has to look at the ground and choose. The pattern moves that decision out of the sled, it does not remove it.

Four parts

  • Strategy

    The interface that all variants share: PaymentStrategy, SortStrategy, CompressionStrategy, ValidationStrategy. In Python an abstract base class or a Protocol.

  • Concrete strategy

    One class per algorithm, with everything that only this algorithm needs: CardPayment, QuickSort, ZipCompression, EmailValidator.

  • Context

    The object that has the job: ShoppingCart, DataSorter, FileCompressor, Navigator. It holds one strategy and delegates to it.

  • Client

    Creates a strategy and hands it over: CheckoutPage, SortingApp, RegistrationForm. The choice is made here.

You use the idea every morning. School is the goal. Walking, the bike, the bus and a lift by car are four strategies. It rains, so today is a bus day. Tomorrow is sunny, so you take the bike. The goal, and the moment you set off, stay the same.

Why

What goes wrong without it

The first version of a feature has one way to do something. The second way arrives as an if. By the fifth, the method is a page long, and unrelated things break together.

Python
class Cart:    def __init__(self):        self.fee = 0    def checkout(self, kind, amount):        if kind == "card":            pass        elif kind == "paypal":            self.fee = amount * 3 // 100        elif kind == "crypto":            if amount < 1000:                return "refused"        return amount + self.fee        # whose fee is this?cart = Cart()print(cart.checkout("paypal", 20000))   # 20600print(cart.checkout("card", 15000))     # 15600: the PayPal fee is still thereprint(cart.checkout("crypt", 15000))    # a typo is also a payment
Run it. Nobody touched the card code, and still the card total is wrong.
Edit and run it in your browser

Two bugs, both made by the shape. The branches share one object, so one leaves its fee behind for the next. And a wrong name falls through every branch and pays nothing at all.

The design that hurts

Cart- cardToken- paypalEmail- wallet- fee: int+ checkout(kind): 3 branches+ refund(kind): 3 branches+ label(kind): 3 branches

1/3One class, every way

Cart holds the data of all payment methods. At any moment two thirds of it mean nothing.

uses

The smell: the same question about a kind, asked in several methods.

One object per way

  • A new way is a new class
  • Each way owns its data
  • Each way has its own small test
  • All questions about one way are answered by one object

Branches in one method

  • Every new way edits working code
  • Branches share fields and leave traces
  • To test one way you load them all
  • The same branches return in refund and label

The idea

Give the algorithm an object of its own

Name what all the ways have in common: the same input, the same kind of answer. That sentence becomes an interface. Each branch becomes a class behind it. The method that had the branches keeps one line.

The Strategy pattern in general

«interface»Strategy+ run(data): Result

1/4The contract

One method, named after the job and not after a way of doing it: run, pay, sort, buildRoute.

useshas (lives on)implements

An open diamond: the strategy comes from outside and may serve other contexts too.
Python
from abc import ABC, abstractmethodclass RouteStrategy(ABC):    @abstractmethod    def build_route(self, origin: str, destination: str) -> list[str]: ...class Navigator:    def __init__(self, strategy: RouteStrategy) -> None:        self._strategy = strategy    def set_strategy(self, strategy: RouteStrategy) -> None:        self._strategy = strategy    def navigate(self, start: str, end: str) -> list[str]:        return self._strategy.build_route(start, end)
The whole pattern on one screen. Navigator never learns which route strategy is active.

Alex drives to the airport

Three times the same call navigate. The answer changes because the object behind the navigator changed. In the old style, each of these three moments would be a branch inside navigate.

The choice

Who chooses the strategy?

The pattern removes the if from the context. It does not remove the decision. Put the decision in exactly one place.

Who choosesExampleGoodCost
The userPayment method, route typeClear and visibleNot every choice is allowed: ask canPay
The client codesorted(people, key=...)Simple, checked by the compilerThe caller knows the classes
A factory or registryConfig says eviction: lruOne place for namesUnknown names must fail at start
The context, from the dataShort list: insertion sortThe caller need not knowThe context knows the classes again
A rule engine or experimentOne percent gets the new rankerSafe rolloutMore moving parts

Where does the branch go that picks the payment strategy?

BreaksStays in the cart
How
if kind == ...: strategy = CardPayment() at the top of checkout.
Limit
The cart still imports every class. You have paid for the pattern and kept the problem.
Choose when
Never.
WorksIn the page that calls the cart
How
The checkout page builds the strategy and injects it.
Limit
A second page, or the mobile app, copies the branch.
Choose when
One caller.
StrongIn one factory or registry
How
methods.create(choice) maps names to constructors. Built once at start, asked at the edge of the program.
Limit
One more object. Unknown names must be refused loudly.
Choose when
Several callers, or names from configuration. See factory.

Shapes

A strategy need not be a class

A strategy with one method and no settings is a function. Languages with first-class functions let you pass it as one. The pattern stays the same, the paperwork goes away.

Python
from typing import CallableDiscount = Callable[[int], int]          # cents in, cents outdef none(total: int) -> int:             # 1. a plain function    return totaldef percent(p: int) -> Discount:         # 2. a closure with a setting    return lambda total: total - total * p // 100class Voucher:                           # 3. an object with state    def __init__(self, cents: int):        self.left = cents    def __call__(self, total: int) -> int:        used = min(self.left, total)        self.left -= used        return total - useddef checkout(total: int, discount: Discount = none) -> int:    return discount(total)voucher = Voucher(1500)print(checkout(2000), checkout(2000, percent(10)))          # 2000 1800print(checkout(1000, voucher), checkout(1000, voucher))     # 0 500
Three shapes of the same strategy: a function, a function that remembers a setting, an object.
Edit and run it in your browser
ShapeUse whenWatch out
Function or lambdaOne method, no stateNo name in logs. Give important ones a name
ClosureOne method, some settingsSettings are hidden, hard to print or compare
ClassSeveral methods, resources, state, a nameNeeds a file and a constructor
Enum with behaviourA fixed small setClosed: others can not add one
Type parameterFixed at compile time, called very oftenNo swap at run time
Two methods that belong together, such as pay and refund, need an object. Two separate functions could be mixed up: paid by card, refunded to PayPal.

Neighbours

State, template method and others

StrategyCompare
StateThe client chooses. Strategies do not know each otherChanges itself from inside as events arrive. States often name the next one. Same drawing, other intent
Template methodThe whole algorithm is replaced, by composition, at run timeSome steps are replaced, by inheritance, fixed when the object is made
CommandHow to do one known jobWhat to do, stored as an object: queue, undo
BridgeOne small algorithm slotTwo whole class families that grow apart
DecoratorChanges the insideWraps the outside, can be stacked
FactoryDoes the workChooses and creates the strategy

Strategy or State?

Choosing

When to use it and when not

Use it when

  • Several algorithms do the same job with the same inputs and outputs
  • The choice is made while the program runs: user, data, configuration
  • Related classes differ only in one behaviour
  • You want to test an algorithm away from the rest
  • Keep strategies without state where possible, so that they can be shared

Leave it when

  • Two or three simple branches that will never change
  • The variants need completely different inputs, so that one interface would be a lie
  • Only a number differs: pass the number
  • A function parameter is enough and you were about to write five classes
  • The context would have to peek into the concrete strategy

How much machinery?

What you pay

  • More names

    Each way is a class or a function with a name. Worth it from the second real variant, not for the first.

  • Clients must know the options

    Somebody has to understand how the ways differ. Describe the trade-off in the name: Fastest, not StrategyB.

  • The widest interface

    All ways get the same arguments. A simple one ignores half of them. If that happens a lot, the family is not a family.

  • One more jump

    A reader of checkout can not see which code runs. Log the name of the strategy with every decision.

Summary

The whole topic in one minute.

If several ways do one job with the same inputs and answers, give the job to a context and each way to an object behind one interface. What differs goes into constructors, what is shared goes into the method.

The choice moves to one place and stays checkable. Read the strategy once per operation, share only what has no state, and fall back only after a certain no.

Start with a function. Use a class when there are several methods, state, or a name to log. Prove with one contract test that every member may stand in for the others.

  • One job, several ways: the job stays in the context, each way becomes an object behind one interface.
  • The context delegates and never asks which strategy it has.
  • The choice does not vanish. It moves to one place: caller, factory or registry.
  • Strategies can be swapped at run time, and each can be tested alone.
  • One method and no state: a function is a strategy.
  • Strategy is chosen from outside. State changes from inside.

Sources