Member-only story
Design Patterns: Using the Strategy Pattern in JavaScript
Design patterns series — part 1
There are 23 classical design patterns described in the book Design Patterns: Elements of Reusable Object-Oriented Software
. These patterns provide a solution to a particular problem, one which is repeated in the software development.
In this piece I will look at the strategy pattern — how it works, how and when it should be apply. This pattern is known as policy in other contexts.
Strategy Pattern: Basic Idea
The strategy pattern is a behavioral design pattern that enables selecting an algorithm at runtime
— Wikipedia
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
— Design Patterns: Elements of Reusable Object-Oriented Software
The main feature of this pattern is that the client has a set of algorithms in which a specific algorithm will be selected for use during runtime. These algorithms are interchangeable between them.
The following code show the classical problem, one in which you need to select a concrete algorithm in your app. In this code, you use the switch
control structure of any programming language.

However, it can be more flexible using the Strategy Pattern which takes the following structure:

The UML’s diagram of this pattern:
Each strategy is represented with a concrete object. So, the client/context contains a Strategy
object (concreteStrategyA
, concreteStrategyB
,…) which implements the interface Strategy
. The key interchange consists in implementing a method in context, which changes the instance of strategy. For example: setStrategy
.