The Strategy pattern is probably the easiest to understand of the Behavioral patterns. We have used it a few times while developing the previous patterns but without stopping to talk about it. Now we will.
The Strategy pattern uses different algorithms to achieve some specific functionality. These algorithms are hidden behind an interface and, of course, they must be interchangeable. All algorithms achieve the same functionality in a different way. For example, we could have a
Sort interface and few sorting algorithms. The result is the same, some list is sorted, but we could have used quick sort, merge sort, and so on.
Can you guess when we used a Strategy pattern in the previous chapters? Three, two, one... Well, we heavily used the strategy pattern when we used the
io.Writer interface. The
io.Writer interface defines a strategy to write, and the functionality is always the same--to write something. We could write it to the standard out, to some file or...