We have seen that the strategy pattern is a powerful design pattern that lets you dissociate algorithms from the objects they operate on. In our example, we could have implemented printing and description with the strategy pattern as well. Instead of implementing CustomStringConvertible with the strings directly, we could have also used a strategy that generates a string that describes the current bill.
With your implementations, you have to keep an eye on:
- Defining the strategy interface carefully. Different strategies may beg for more complex interfaces; once the strategy interface is defined, refactoring may be very costly.
- Minimizing the logic inside the Context object. In our case, the Bill was very simple.
- Mutations - strategies can mutate the context, changing the current strategy in turn. In this example, we manipulated the bill strategy from the outside, but equally we could have mutated the strategy inside the strategy itself. This implementation is also interesting, as it keeps the logic outside the core objects.