Strategy
Last updated
Last updated
Strategy is a behavioral design pattern that lets you define a family of algorithms, put each of them into a separate class, and make their objects interchangeable.
The Strategy design pattern is a behavioral design pattern that allows you to define a family of algorithms, encapsulate each one of them, and make them interchangeable.
It lets the algorithm vary independently from clients that use it.
The Strategy design pattern is used to define a family of algorithms, encapsulate each algorithm, and make them interchangeable.
The pattern lets the algorithm vary independently from the context that uses it. Here's a simple example in JavaScript:
In this example:
operationAdd
, operationSubtract
, and operationMultiply
are the different strategies that encapsulate the algorithms for addition, subtraction, and multiplication.
Context
is the class that takes a strategy and uses it to execute the desired operation.
By changing the strategy in the Context
constructor, you can switch between different operations without changing the Context
class itself, demonstrating the flexibility and interchangeability of algorithms in the Strategy pattern.