The Strategy design pattern
The Strategy pattern is a behavioral design pattern that allows us to change object behaviors at runtime.
We can also use this pattern to compose complex object trees and rely on it to follow the Open/Closed Principle (OCP) without much effort. Moreover, it plays a significant role in the composition over inheritance way of thinking and is the backbone of dependency injection.
In this chapter, we focus on the behavioral part of the Strategy pattern. The next chapter covers how to use this pattern to compose systems dynamically.
Goal
The Strategy pattern aims to extract an algorithm (a strategy) from the host class that needs it (the context or consumer). That allows the consumer to decide on the strategy (algorithm) to use at runtime.
Design
Before any further explanation, let’s take a look at the following class diagram:
Figure 7.1: Strategy pattern class diagram
Based on the preceding diagram, the building...