Skip to content

Strategy Pattern

In one line

The Strategy pattern defines a family of interchangeable algorithms and lets the client choose one at runtime.

In simple words

The Strategy pattern defines a set of algorithms, encapsulates each one, and makes them interchangeable. The client code works against a common interface and can swap the concrete strategy without changing its own logic. This is useful when you have multiple ways to do the same thing and want to select the approach dynamically.

For example, a payment system might support credit card, PayPal, and crypto strategies. The checkout code calls payStrategy.process(amount) and does not care which concrete strategy is plugged in. You can add a new payment method by writing a new strategy class without touching the checkout logic.

Strategy eliminates long if/else or switch chains that pick behavior. It also isolates each algorithm in its own class, making them independently testable and reusable across the application.

Example

javascript
const strategies = {
  add: (a, b) => a + b,
  multiply: (a, b) => a * b,
  max: (a, b) => Math.max(a, b),
};

function calculate(strategy, a, b) {
  return strategies[strategy](a, b);
}

console.log(calculate("add", 3, 4));       // 7
console.log(calculate("multiply", 3, 4)); // 12
console.log(calculate("max", 3, 4));      // 4

The strategy is chosen by name at runtime. calculate() delegates to the selected algorithm without knowing its details.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary