To conclude this chapter, we'll cover the strategy pattern. This design pattern lets you write programs that are able to select different algorithms or strategies at runtime. For example, using the strategy pattern may help in sorting objects in different ways, by letting you specify the comparison function at runtime.
You will find yourself wanting to implement the strategy pattern when faced with:
- Complex classes with multiple algorithms changing at runtime
- Algorithms that may improve performance and need to be swapped at runtime
- Multiple implementations of similar algorithms in different classes, making them difficult to extract
- Complex algorithms that are strongly tied to data structures
The goal of the strategy pattern is to let you isolate those algorithms from the context they operate in.