Swapping Algorithms with the Strategy Pattern
In the last chapter, we used the Visitor pattern to apply different behavior to objects without changing the underlying object itself. In this chapter, we’re going to explore how the Strategy pattern lets us configure classes with interchangeable algorithms (or behaviors) at runtime. Not only is this a fantastic way to define different variants of a given algorithm but also your client code doesn’t need to worry about each algorithm’s internal state or data dependencies.
I love this pattern because we use strategies in real life all the time! Think of the moments before you leave the house – it’s always a good idea to check the weather to decide whether you need a coat if it’s cold, an umbrella if it’s going to rain, or extra sunblock if it’s scorching hot. Each possibility has its own strategy (cold weather, stormy weather, or hot weather), but you can choose whichever one fits...