Strategy Pattern
The Strategy Pattern is a behavioral design pattern that defines a family of interchangeable algorithms and allows the algorithms to be selected at runtime based on client requirements. The idea is to encapsulate a set of related algorithms and to make them interchangeable without the client being aware of the details of each algorithm.
In JavaScript, the Strategy Pattern can be implemented by defining a set of strategy classes, each containing an algorithm that performs a specific task. The client can then select a strategy based on some parameter, and based on the selected strategy, the appropriate algorithm will be executed.
Here’s an example of how the Strategy Pattern can be implemented in JavaScript:
// Define a set of strategies
class AddStrategy {
execute(a, b) {
return a + b;
}
}
class SubtractStrategy {
execute(a, b) {
return a - b;
}
}
class MultiplyStrategy {
execute(a, b) {
return a * b;
}
}
// Client code
class Calculator {
constructor(strategy) {
this.strategy = strategy;
}
setStrategy(strategy) {
this.strategy = strategy;
}
calculate(a, b) {
return this.strategy.execute(a, b);
}
}
// Using the Calculator with different strategies
const calculator = new Calculator(new AddStrategy());
console.log(calculator.calculate(5, 3)); // Output: 8
calculator.setStrategy(new SubtractStrategy());
console.log(calculator.calculate(5, 3)); // Output: 2
calculator.setStrategy(new MultiplyStrategy());
console.log(calculator.calculate(5, 3)); // Output: 15In this example, we first define a set of strategy classes -
AddStrategySubtractStrategyMultiplyStrategyeach containing a different algorithm that performs an arithmetic operation.
Get Anant Nema’s stories in your inbox
Join Medium for free to get updates from this writer.
We then define a
Calculatorclass that accepts a strategy in its constructor and provides a
calculate()method that executes the strategy’s algorithm, which takes two numbers as parameters.
The client can then create an instance of the
Calculatorclass with a specific strategy and use the
calculate()method to perform arithmetic operations.
By encapsulating the algorithms into strategy classes, we make it easier to change the behavior of the calculator without having to modify the client code.




