The Strategy pattern is intended to provide you with a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable.

image

This is one of my favorite design patterns, because it provides you a way to encapsulate a strategy. This comes in very handy when you suspect that there will be a strategy update in the near future. For example, you could use this pattern for report engine selection.

The client first creates a context, in which a strategy is injected. In this simplified example a result is returned by a method called ContextInterface. Independent of the strategy selected, invocation of the method and collecting its result remains the same.

An abstract class Strategy defines an algorithm interface as a method.

The concrete classes implement the abstract method.

The Context class contains a strategy, which is injected upon instantiation. The public method ContextInterface provide a way to call the algorithm interface of the encapsulated strategy.

You see? It is a relatively simple pattern and similar to the factory method pattern. In my humble opinion there is not much difference between them.

This post is part of a series on the foundational design patterns in C#. In this series we explore the ancient design patterns and their use in real-world programming situations of today. In these series of posts we explore each pattern by looking at a minimalistic example to reveal its structure and then look at more concrete and useful real-world C# code that implements the pattern.