The primary goal of the Strategy pattern is to defer the decision of which behavior to use at runtime. This is made possible because the Strategy pattern lets us define a family of behaviors that are encapsulated in individual classes that we call strategies. Each strategy is interchangeable and can be assigned to a target context object to change its behavior.
Let's visualize the key elements of the pattern with this UML diagram:
Figure 11.1 – UML diagram of the Strategy pattern
Here's a breakdown of the key players of the pattern:
- Context is the class that uses the various concrete strategy classes and interacts with them through the Strategy interface.
- The Strategy interface is common to all concrete strategy classes. It exposes a method that the Context class can use to execute a strategy.
- Concrete Strategy classes, also known as strategies, are concrete implementations of variants of algorithms/behaviors that ...