0
0
JavascriptConceptBeginner · 3 min read

Strategy Pattern in JavaScript: What It Is and How It Works

The strategy pattern in JavaScript is a design approach that lets you choose an algorithm or behavior at runtime by encapsulating each one in separate objects. It helps keep code flexible and easy to change by swapping strategies without changing the main code.
⚙️

How It Works

Imagine you have different ways to do the same task, like paying for a meal with cash, card, or mobile pay. The strategy pattern lets you pick the payment method without changing the main checkout process. Each payment method is a separate strategy.

In JavaScript, this means you create different functions or objects for each behavior and then select which one to use when needed. This keeps your code clean and easy to update because you can add or change strategies without touching the main logic.

💻

Example

This example shows a simple calculator that can add or multiply numbers by choosing the strategy at runtime.

javascript
class Calculator {
  constructor(strategy) {
    this.strategy = strategy;
  }

  setStrategy(strategy) {
    this.strategy = strategy;
  }

  execute(a, b) {
    return this.strategy(a, b);
  }
}

const addStrategy = (a, b) => a + b;
const multiplyStrategy = (a, b) => a * b;

const calculator = new Calculator(addStrategy);
console.log(calculator.execute(5, 3)); // 8

calculator.setStrategy(multiplyStrategy);
console.log(calculator.execute(5, 3)); // 15
Output
8 15
🎯

When to Use

Use the strategy pattern when you have multiple ways to perform a task and want to switch between them easily without changing your main code. It is helpful when you expect new behaviors to be added later or want to keep your code organized.

For example, it works well for payment methods, sorting algorithms, or different ways to validate user input. It makes your code flexible and easier to maintain.

Key Points

  • The strategy pattern separates algorithms into different objects or functions.
  • It allows changing behavior at runtime without modifying the main code.
  • It improves code flexibility and maintainability.
  • It is useful when multiple interchangeable behaviors exist.

Key Takeaways

The strategy pattern lets you swap algorithms or behaviors easily at runtime.
It keeps your code clean by separating different ways to do a task into separate strategies.
Use it when you want flexible and maintainable code with interchangeable behaviors.
It is ideal for cases like payment methods, sorting, or validation where multiple options exist.