Strategy Design Pattern Explained
Strategy defines a family of interchangeable algorithms, encapsulating each one and letting the algorithm vary independently from the code that uses it.
Published November 12, 2026
The Strategy pattern defines a family of interchangeable algorithms behind a common interface and lets you pick one at runtime. It replaces big if/else or switch chains.
The concept
Each algorithm lives in its own class or function. The caller holds a reference to a strategy and delegates the work.
Adding a new behaviour means adding a strategy, not editing existing code.
Swap behaviour at runtime
Practical examples
Functions as strategies
const pay = {
card: (amt) => chargeCard(amt),
upi: (amt) => chargeUpi(amt),
}
pay[method](100)Class-based
interface Discount { public function apply(float $p): float; }
class Sale implements Discount { public function apply(float $p): float { return $p * .9; } }
class Cart { function __construct(private Discount $d) {} function total($p) { return $this->d->apply($p); } }Sorting
items.sort((a, b) => a.price - b.price) // comparator is a strategyCommon mistakes
- Using it for a two-branch if.
- Strategies that need too much context data.
- Forgetting a default strategy.
Key takeaways
- Interchangeable algorithms behind one interface.
- Removes switch chains.
- Open for extension.
FAQ
Strategy vs State?
Strategy is chosen by the client; State changes by itself as the object's state changes.
Do I need classes?
No, functions work in many languages.