Strategy Pattern C#

Strategy is a behavioural design pattern, It’s used when Class have different implementation of the method, depended on the context. Here is formal definition of the pattern:

 Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

In order to understand the concept you should be familiar with principles of object oriented programming. Family of algorithms have the same function but different ways to execute it.  Strategy pattern can select the way of implementing the method from possible options in run time. I’ll be more clear after demonstrating the example.

UML class diagram:

Strategy

 

 

 

 

 

 

To demonstrate the use of this pattern I will create Program Class that executes one of methods, depended on the context.

Strategy can be implemented as Abstract Class or Interface. In this example i will use abstract class. Just like this.

abstract class Strategy
{
  public abstract void AlgorithmInterface();

So now we need to crate implementations of this method.

Each class inherits from Abstract Class and provides different implementation that will print the name of the class to the console.

class ConcreteStrategyA : Strategy
{
  public override void AlgorithmInterface()
  {
     Console.WriteLine("ConcreteStrategyA");
  }
}

class ConcreteStrategyB : Strategy
{
  public override void AlgorithmInterface()
  {
      Console.WriteLine("ConcreteStrategyB");
  }
}

class ConcreteStrategyC : Strategy
{
  public override void AlgorithmInterface()
  {
     Console.WriteLine("ConcreteStrategyC");
  }

Now let’s create a context of this behaviour

class Context
{
  private Strategy _strategy;

  // Constructor
  public Context(Strategy strategy)
  {
     this._strategy = strategy;
  }

  public void ContextInterface()
  {
     _strategy.AlgorithmInterface();
  }

When we crate instance of this Class we pass the strategy implementation that will be selected. Last part of the program is the Program Class that will connect everything together.

class Program
{
  static void Main()
  {
    Context context;
    context = new Context(new ConcreteStrategyA());
    context.ContextInterface();

    context = new Context(new ConcreteStrategyB());
    context.ContextInterface();

    context = new Context(new ConcreteStrategyC());
    context.ContextInterface();
  }

Here we create three instances of the Context Class, each one with different implementation of the Strategy interface.

It was example of structural code that represent the bare bones implementation of this pattern. In next part I’ll use more practical examples of implementation. Stay Awesome!