Strategy Design Pattern

Strategy is probably one of the easiest patterns to understand. And even it is pretty simple to provide examples for it, since it can be used almost everywhere you like. So, this article will be short.

First of all, what is the purpose of Strategy? Basically, you use Strategy when you are pretty sure that you are going to need different types of algorithms on the same input. In other words, you provide some abstraction which would operate on the same data, e.g. some list which you might want to sort in ascending order in one scenario, and in descending order in another scenario.

So, let us take a look into the actual example.

// You do not care here about the algorithm. You just know you want the data to get sorted somehow.
interface ISortingAlgorithm
{
    void SortData(List<Data> data);
}
 
// Here, you might want to know some sorting way.
class SortingContext
{
    ISortingAlgorithm GetSortingAlgorithm(int algorithm)
    {
        if (algorithm == 2) return new DescendingSortingAlgorithm();
 
        return new AscendingSortingAlgorithm();
    }
}

Your client would use just SortingContext, and he/she would know nothing of the actual algorithm being used. So, this is it regarding Strategy Design pattern. As I have just told you, it is really simple one.

For more examples if you like, the following sources are pretty good regarding Strategy:

  1. https://en.wikipedia.org/wiki/Strategy_pattern
  2. https://www.tutorialspoint.com/design_pattern/strategy_pattern.htm
  3. https://sourcemaking.com/design_patterns/strategy

Leave a Reply

Your email address will not be published. Required fields are marked *