Strategy Pattern
Learn how to use the Strategy pattern to create a configuration manager that supports various file formats.
We'll cover the following...
The Strategy pattern enables an object, called the context, to support variations in its logic by extracting the variable parts into separate, interchangeable objects called strategies. The context implements the common logic of a family of algorithms, while a strategy implements the mutable parts, allowing the context to adapt its behavior depending on different factors, such as an input value, a system configuration, or user preferences.
Strategies are usually part of a family of solutions and all of them implement the same interface expected by the context. The following figure shows the situation we just described:
The above illustration shows us how the context object can plug different strategies into its structure as if they were replaceable parts of a piece of machinery. Imagine a car; its tires can be considered its strategy for adapting to different road conditions. We can fit winter tires to go on snowy roads thanks to their studs, while we can decide to fit high-performance tires for traveling mainly on motorways for a long trip. On the one hand, we don’t want to change the entire car for this to be possible, and on the other, we don’t want a car with eight wheels so that it can go on every possible road.
We quickly understand how powerful this pattern is. Not only does it help with separating the concerns within a given problem, but it also enables our solution to have better flexibility and adapt to different variations of the same ...