Strategy pattern
medium 55 minDefine a family of interchangeable algorithms behind one interface.
Video lesson · Chapter 1 of 6
Make a prediction
Strategy
1:02Reel

More reels
One idea each, a minute or less.
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
1994
The book Design Patterns lists Strategy among its behavioral patterns.
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.
2014
Java 8 brings lambda expressions (JEP 126). A Comparator can now be written in one line.
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.
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.
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 aProtocol.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.
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 paymentTwo 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
1/3One class, every way
Cart holds the data of all payment methods. At any moment two thirds of it mean nothing.
uses
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
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
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)Navigator never learns which route strategy is active.Alex drives to the airport
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 chooses | Example | Good | Cost |
|---|---|---|---|
| The user | Payment method, route type | Clear and visible | Not every choice is allowed: ask canPay |
| The client code | sorted(people, key=...) | Simple, checked by the compiler | The caller knows the classes |
| A factory or registry | Config says eviction: lru | One place for names | Unknown names must fail at start |
| The context, from the data | Short list: insertion sort | The caller need not know | The context knows the classes again |
| A rule engine or experiment | One percent gets the new ranker | Safe rollout | More moving parts |
Where does the branch go that picks the payment strategy?
BreaksStays in the cart
- How
if kind == ...: strategy = CardPayment()at the top ofcheckout.- 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.
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| Shape | Use when | Watch out |
|---|---|---|
| Function or lambda | One method, no state | No name in logs. Give important ones a name |
| Closure | One method, some settings | Settings are hidden, hard to print or compare |
| Class | Several methods, resources, state, a name | Needs a file and a constructor |
| Enum with behaviour | A fixed small set | Closed: others can not add one |
| Type parameter | Fixed at compile time, called very often | No swap at run time |
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
| Strategy | Compare | |
|---|---|---|
| State | The client chooses. Strategies do not know each other | Changes itself from inside as events arrive. States often name the next one. Same drawing, other intent |
| Template method | The whole algorithm is replaced, by composition, at run time | Some steps are replaced, by inheritance, fixed when the object is made |
| Command | How to do one known job | What to do, stored as an object: queue, undo |
| Bridge | One small algorithm slot | Two whole class families that grow apart |
| Decorator | Changes the inside | Wraps the outside, can be stacked |
| Factory | Does the work | Chooses 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, notStrategyB.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
checkoutcan 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
- Design Patterns (publisher page)
- Refactoring catalog: Replace Conditional with Polymorphism
- Wikipedia: Strategy pattern
- Python abc module
- PEP 544: Protocols
- Java Comparator
- Java RejectedExecutionHandler
- Redis key eviction
- Spring Security password storage
- Passport.js strategies
- Kafka producer settings
- gRPC custom load balancing