What is the Strategy pattern and how does it help avoid large if/else chains?
Short answer
Strategy defines a family of interchangeable algorithms/behaviors as separate functions or objects, and lets you swap which one is used at runtime, replacing sprawling conditional logic with a simple lookup or injected dependency.
Advertisement
AModel answer
Strategy defines a family of interchangeable algorithms/behaviors as separate functions or objects, and lets you swap which one is used at runtime, replacing sprawling conditional logic with a simple lookup or injected dependency.
const strategies = {
card: (amt) => payWithCard(amt),
paypal: (amt) => payWithPaypal(amt),
};
function pay(method, amount) {
return strategies[method](amount);
}Real-world example
Supporting multiple payment or shipping calculation methods that can be swapped without touching the core checkout logic.
Likely follow-ups
- How does Strategy relate to dependency injection?
Related topics