The Strategy Pattern Explained With Practical Examples
The strategy pattern swaps algorithms at runtime behind a common interface. Learn how it works, when it beats conditionals, and its trade-offs.
By Velloreth
The problem: growing conditionals
Suppose you are calculating shipping costs, and the rules differ by method.
function shippingCost(method: string, weight: number): number {
if (method === 'standard') {
return weight * 0.5;
} else if (method === 'express') {
return weight * 2 + 10;
} else if (method === 'overnight') {
return weight * 5 + 25;
} else if (method === 'international') {
return weight * 3 + 40;
}
throw new Error(`Unknown method: ${method}`);
}
This works, and for four cases it is perfectly readable. The problems appear as it grows:
- Every new method edits this function, so it must be re-tested.
- The function mixes four unrelated pricing rules in one place.
- The rules cannot be tested in isolation.
- The method name is a string, so a typo is a runtime error.
The strategy pattern addresses all four.
The pattern
Define an interface for the algorithm, one implementation per variant, and a context that holds one and delegates to it.
interface ShippingStrategy {
cost(weight: number): number;
}
class StandardShipping implements ShippingStrategy {
cost(weight: number) { return weight * 0.5; }
}
class ExpressShipping implements ShippingStrategy {
cost(weight: number) { return weight * 2 + 10; }
}
class OvernightShipping implements ShippingStrategy {
cost(weight: number) { return weight * 5 + 25; }
}
class Order {
constructor(private shipping: ShippingStrategy) {}
shippingCost(weight: number): number {
return this.shipping.cost(weight);
}
}
Order is the context. It holds a strategy and delegates. It does not know which pricing rule it is using, and it does not need to.
Adding a new method is a new class. Nothing existing changes.
The functional form
In a language with first-class functions, the interface is just a function type.
type ShippingStrategy = (weight: number) => number;
const standard: ShippingStrategy = (w) => w * 0.5;
const express: ShippingStrategy = (w) => w * 2 + 10;
const overnight: ShippingStrategy = (w) => w * 5 + 25;
class Order {
constructor(private shipping: ShippingStrategy) {}
shippingCost(weight: number) {
return this.shipping(weight);
}
}
const order = new Order(express);
This is the same pattern with far less ceremony. There is no interface declaration, no class per variant, and no implements clause. The function type is the contract.
In JavaScript, Python, Ruby, and Go, this is usually the right form. The class-based version is idiomatic in Java and C# because those languages historically lacked first-class functions.
A registry instead of a switch
If you still need to look up a strategy by name, use a map rather than a switch.
const strategies: Record<string, ShippingStrategy> = {
standard,
express,
overnight,
};
function getStrategy(method: string): ShippingStrategy {
const strategy = strategies[method];
if (!strategy) {
throw new Error(`Unknown method: ${method}. Valid: ${Object.keys(strategies).join(', ')}`);
}
return strategy;
}
The registry is data, not control flow. Adding a method is adding a key. The error message lists the valid options automatically, which is a small but real usability win.
Where the pattern appears
Payment processing. Each provider has its own charge logic behind a common interface.
Pricing rules. Discounts, taxes, and shipping vary by region, customer tier, and promotion.
Sorting and comparison. A comparator is a strategy. Array.prototype.sort takes one.
Compression. Choosing gzip, brotli, or none based on content type.
Authentication. Password, OAuth, SSO, and API key are interchangeable strategies.
Validation. Different rules for different form fields or document types.
Retry policies. Fixed delay, exponential backoff, and no retry are strategies.
Rendering. Server-side, client-side, and static rendering behind one interface.
The common thread is a task with several valid approaches, chosen at runtime.
Strategy versus conditionals
The honest comparison: for a small, fixed set of cases, a conditional is clearer.
// Two cases: a conditional is fine
function format(value: number, style: 'plain' | 'currency'): string {
return style === 'currency' ? `$${value.toFixed(2)}` : String(value);
}
Wrapping this in two classes and an interface would be worse. The conditional is three lines, has no indirection, and the reader sees everything.
The strategy pattern starts to pay when:
- There are more than about four cases.
- Each case has real logic, not one expression.
- The cases change independently.
- You need to test each case in isolation.
- The set is likely to grow.
- The choice is made at runtime from data.
The threshold is judgement, not a rule. The signal to watch is a conditional that keeps growing and that you keep having to re-test.
Strategy versus state
Both patterns delegate to a swappable object, which makes them easy to confuse.
Strategy: the client chooses the algorithm, and it usually stays fixed for the object’s lifetime. An Order is created with a shipping strategy and keeps it.
State: the object changes its own behaviour as it transitions between states. A Connection moves from connecting to open to closed, and each state handles the same methods differently.
The distinguishing question: who decides the swap? If the client does, it is strategy. If the object does, based on its own state, it is state.
The trade-offs
Indirection. The code that runs is not visible at the call site. You must find where the strategy was injected to know what happens.
More types. Each strategy is a class or a named function. For four cases, that is four more names to learn.
Over-abstraction risk. A strategy interface with one implementation is ceremony. Wait for the second case.
Runtime errors. A string-keyed registry can fail at runtime if the key is wrong. A typed union or an enum reduces this.
Debugging. Stack traces go through the delegation, adding a frame. Usually harmless, occasionally confusing.
Practical guidance
- Use a function type as the strategy interface where the language allows it.
- Use a registry map rather than a switch when looking up by name.
- Inject the strategy so it can be faked in tests.
- Keep each strategy small — one algorithm, one class.
- Do not abstract a two-case conditional.
- Type the strategy key as a union or enum to catch typos at compile time.
- Document which strategies exist where the choice is made.
For the related patterns, see design patterns for beginners and factory pattern explained. For the design principles, SOLID principles explained and composition vs inheritance.
Quotable summary
The strategy pattern defines a family of interchangeable algorithms behind a common interface, letting the choice be made at runtime. It replaces growing conditional chains with small, independently testable implementations, and the context object delegates without knowing which algorithm it holds. In languages with first-class functions, a strategy is usually just a function type, which removes most of the ceremony, and a registry map is preferable to a switch when looking up by name. The pattern adds indirection, so it earns its keep when there are more than a few cases, each with real logic, and the set is likely to grow. For a small, fixed set of cases, a plain conditional is clearer.