The Strategy Pattern
You'll learn how to swap out algorithms on the fly without changing the code that uses them.
What Is the Strategy Pattern?
The Strategy Pattern lets you define a family of related algorithms, encapsulate each one in its own function or object, and make them interchangeable at runtime. Instead of hardcoding a specific approach, you pass in the strategy you want to use.
Think of it like choosing a payment method at checkout: credit card, PayPal, or gift card. The checkout process stays the same, but the payment strategy changes based on what you select.
Why Use It?
Without this pattern, you'd end up with messy conditionals (if/else or switch statements) scattered throughout your code. The Strategy Pattern replaces that with clean, pluggable behavior.
Basic Example
// Define different sorting strategies
const bubbleSort = (arr) => { /* implementation */ };
const quickSort = (arr) => { /* implementation */ };
// Context that uses a strategy
function sortData(data, strategy) {
return strategy(data);
}
// Use different strategies
sortData([3, 1, 2], bubbleSort);
sortData([3, 1, 2], quickSort);
With Objects
You can also use objects to group related strategies:
const shippingStrategies = {
standard: (weight) => weight * 0.5,
express: (weight) => weight * 1.5,
overnight: (weight) => weight * 3.0
};
function calculateShipping(weight, strategy) {
return shippingStrategies[strategy](weight);
}
calculateShipping(10, 'express'); // 15
Key Takeaway: The Strategy Pattern eliminates conditional complexity by making behaviors interchangeable—pass in the algorithm as a parameter instead of hardcoding decisions.