The second pattern I want to discuss is the
strategy pattern, which provides a way to configure a
class with one of many behaviors. What does that
mean? Well, more precisely, this pattern allows for defining
a family of algorithms, encapsulating them into separate classes,
so each algorithm in one class, and making these
classes interchangeable, but providing a common interface for all
the encapsulated algorithms. So in essence, the intent of
a strategy pattern is to allow for switching between
different algorithms for accomplishing a given task. For example, imagine
having different sorting algorithms with different space or time
tradeoffs. You might want to be able to have them
all available and use different ones in different situations.
And this pattern is applicable not only when we have
different variants of an algorithm, but also when we
have many related classes that differ only in their behavior.
So let's get more concrete and see how this is
done. And I'm going to do it as before, by
discussing the structure and the participants for this strategy pattern.
In this case, we have 3 types of participants for this
pattern, the context, the algorithm, and the concrete strategies. There
can be as many as the number of behaviors that
I need to implement. So, let's see what those are.
The context is the interface to the outside world. It maintains
a reference to the current algorithm and allows for
updating this reference at run time. So, basically the outside
world will invoke the functionality provided by the different algorithms,
by using this interface. And depending on which algorithm is
currently selected, that's the one that will be executed when
the functionality is involved. The algorithm, also called the strategy,
so that's where the pattern gets its name, Is the
common interface for the different algorithims. So all the algorithms
implement this interface. Finally, the concrete strategies are the
actual implementations of the algorithms. So if I have 10
different variants of my algorithm, I will implement 10 different
concrete strategies. They will all be implementations of this interface.