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.
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class MainApp { static void Main() { Context context; Strategy strategy = new FirstConcreteStrategy(); context = new Context(strategy); string result = context.ContextInterface(); Console.WriteLine(result); strategy = new SecondConcreteStrategy(); context = new Context(strategy); result = context.ContextInterface(); Console.WriteLine(result); Console.ReadKey(); } } |
An abstract class Strategy defines an algorithm interface as a method.
|
1 2 3 4 5 |
abstract class Strategy { public abstract string AlgorithmInterface(); } |
The concrete classes implement the abstract method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class FirstConcreteStrategy : Strategy { public override string AlgorithmInterface() { return "FirstConcreteStrategy"; } } class SecondConcreteStrategy : Strategy { public override string AlgorithmInterface() { return "SecondConcreteStrategy"; } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
class Context { private Strategy m_Strategy; public Context(Strategy strategy) { this.m_Strategy = strategy; } public string ContextInterface() { return m_Strategy.AlgorithmInterface(); } } |
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.
Comments