The Strategy pattern explained: one job, swappable behaviours. A Python example, swapping at runtime, functions as strategies, and when a plain if is better.
Strategy pattern explained by cats. Kitty loves to hunt. Sometimes she attacks, sometimes she sneaks, sometimes she hides and waits. The goal is the same. Catch the toy mouse. But the tactic changes. That's the strategy pattern. You define one action, let's say hunt.
Then you plug in different strategies, like attack, sneak, or wait. Kitty can swap tactics at runtime. No need to rewrite the hunt method. Calls a strategy interface. Each tactic such as attack, sneak, wait, implements that interface. Switch strategies on the fly.
Strategy pattern is having the same goal, but different behaviors. Perfect when you need flexible, swappable algorithms. That's the strategy pattern.
The Strategy pattern keeps one job fixed and makes the way it gets done swappable: each way of doing the job lives in its own small object, and you pick the one you need at runtime.
You write the job once, so adding a new behaviour never means editing the code that uses it.
The problem it solves
Most code that needs a strategy starts life as a conditional. Say an online shop works out delivery costs at checkout:
This is fine with three options. Then the business adds next-day, then international, then a free-delivery promotion with its own rules. Every new option means opening the same function, adding another branch and retesting all the others. The checkout code knows the details of every delivery method, and each branch can break its neighbours.
Strategy pattern explained by cats. Kitty loves to hunt. Sometimes she attacks, sometimes she sneaks, sometimes she hides and waits. The goal is the same. Catch the toy mouse. But the tactic changes. That's the strategy pattern. You define one action, let's say hunt.
Then you plug in different strategies, like attack, sneak, or wait. Kitty can swap tactics at runtime. No need to rewrite the hunt method. Calls a strategy interface. Each tactic such as attack, sneak, wait, implements that interface. Switch strategies on the fly.
Strategy pattern is having the same goal, but different behaviors. Perfect when you need flexible, swappable algorithms. That's the strategy pattern.
The Strategy pattern pulls those branches apart. The job (work out a delivery cost) stays in one place. Each way of doing it becomes a separate, interchangeable piece.
How the pattern fits together
There are three parts:
The strategy interface: the one method every option must provide. Here, cost(weight_kg).
Concrete strategies: one class (or function) per option, each implementing that method its own way.
The context: the code that does the overall job. It holds a reference to a strategy and calls it, without knowing which one it has.
The context depends only on the interface. Because it never names a concrete strategy, you can hand it any of them.
The relationships look like this:
Checkout depends only on the highlighted interface, never on a concrete strategy.
This is composition rather than inheritance. Checkout doesn't subclass anything to change its behaviour; it has a strategy and delegates to it.
A worked example in Python
First, the interface. In Python a Protocol describes the shape a strategy must have:
Checkout.total is written once and never changes. Adding next-day delivery means writing a new NextDay class with a cost method. Nothing in Checkout is touched, and nothing about Standard or Express can break.
Swapping at runtime
The line order.shipping = Express() is where the flexibility shows. The same Checkout object changes how it behaves while the program runs, because its behaviour lives in whatever strategy it currently holds. A customer can switch delivery method on the payment page and the total updates, with no new checkout object and no new code path.
Something still has to choose
The conditional doesn't disappear completely: something has to pick which strategy to use. The difference is that the choice now happens once, at the edge of the program, usually as a lookup rather than a chain of branches:
Adding a delivery method is now a new class plus one line in this table. Each method's pricing rules sit in their own class, and the code that runs the checkout stays the same.
Functions can be strategies too
In languages with first-class functions (Python, JavaScript, C#, Kotlin), a strategy doesn't have to be a class. A function with the right signature does the same job, and you have almost certainly used one already.
Python's sorted is a context, and its key argument is the strategy:
The sorting algorithm is the same both times. Only the rule for comparing items changes. JavaScript's array.sort(compareFn) and the comparers in C# work the same way.
Use a function when the strategy is one small calculation with no state. Reach for classes when a strategy needs configuration (a rate, an API client), several related methods, or a name that shows up clearly in tests and logs.
How it relates to other patterns
Passing the strategy into Checkout's constructor, instead of having Checkout create it, is dependency injection. The two often appear together: DI hands the context its strategy, and the shared interface is what lets you hand it a different one.
The Decorator pattern also puts behaviour behind an interface, but for a different job. A decorator wraps an object to add something around it (logging, caching) and keeps the original behaviour. A strategy replaces the core algorithm.
The State pattern has the same structure as Strategy, which is why the two get confused. In State, the object switches its own behaviour as its internal state changes (an order moving from 'paid' to 'shipped'). In Strategy, the caller picks the behaviour, and the strategies usually don't know about each other.
Template Method solves the same problem with inheritance: a base class fixes the steps and subclasses override some of them, so the behaviour is set when the object is created. Strategy uses composition, so the behaviour can change later.
When to use it
Strategy earns its place when:
you have several ways of doing the same job, and you expect more;
the choice depends on user input, configuration or data, and can change at runtime;
a growing if/elif or switch on a 'type' or 'mode' value keeps getting edited;
you want to test each behaviour on its own, without setting up the whole context.
Payment providers, pricing and discount rules, file export formats, compression algorithms, retry policies and route planners (fastest, shortest, avoid tolls) are all common fits.
It is the wrong tool when there are only two options that are unlikely to change. A plain if is easier to read than an interface, three classes and a lookup table. Patterns cost indirection: someone reading self.shipping.cost(...) has to go and find out which strategy is in play.
Common mistakes
Adding it too early: wrapping a single algorithm in an interface 'in case' another one turns up adds files and indirection for no gain. Start with the simple version and extract strategies when the second or third option arrives.
Making the interface take everything: if one strategy needs the customer's address and another needs the basket, a shared method that takes both ends up with arguments most strategies ignore. Pass what the job needs, and give each strategy its own settings through its constructor.
Checking the type in the context: code like if isinstance(self.shipping, Express) inside Checkout brings back the conditional the pattern removed. If the context needs to know which strategy it has, the interface is missing a method.
Sharing mutable state: a strategy instance in a lookup table is shared by every caller. Keep strategies stateless, or create a fresh one per use when they must hold data.
Key takeaways
Strategy separates what a job does from how it gets done.
The context depends only on an interface, so you can add strategies without editing it.
Strategies can be swapped at runtime, and the choice of which to use moves to one place.
In Python and JavaScript, a plain function (like sorted's key) is often enough.
Don't use it for two options that will never change: a simple if reads better.