Implementing the strategy pattern
The strategy pattern allows an algorithm to be selected at runtime based on the needs of the application. Instead of using the if
type statements to select an algorithm, the algorithm's implementation is contained in classes that implement an interface depicting the desired operation. This allows the algorithm executed to vary depending on the client it is applied against.
The pattern does not use inheritance, but rather encapsulates the behavior in another class. This composition approach decouples the behavior from the classes that use the behavior. Changing the behavior does not affect the class that uses it.
Let's assume that a list of tasks needs to be processed. However, there are various task ordering algorithms that can be used. The idea is to associate a list of tasks with a specific algorithm. The algorithm can then be applied to decide which task should be used executed next.
We will illustrate this pattern by showing how to implement scheduling...