Strategy Pattern in .NET

Last week I researched the Strategy design pattern and thought to share my knowledge with you all.

The Strategy design pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Intent

The intent of the Strategy design pattern helps us to divide an algorithm from a host class and then move it to another class. By doing so the client can choose which algorithm will be performed in runtime from a set of algorithms that were implemented earlier.

Motivation & Applicability

There are common situations when classes differ only in their behaviour. For this case, it is a good idea to isolate the algorithms in separate classes in order to have the ability to select different algorithms at runtime. The Strategy pattern allows us to provide an alternative to subclassing the Context class to get a variety of algorithms or behaviours, eliminates large conditional statements and provides a choice of implementations for the same behaviour.
 
Use the Strategy pattern whenever:
  • Many related classes differ only in their behaviour
  • You need different variants of an algorithm
  • An algorithm uses data that clients shouldn't know about. Use the Strategy pattern to avoid exposing complex, algorithm-specific data structures.
  • A class defines many behaviors, and these appear as multiple conditional statements in its operations. Instead of many conditionals, move related conditional branches into their own Strategy class.
The classes and/or objects participating in this pattern are:
  • Strategy (CalculateStrategy using ICalculateInterface) - declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy
  • ConcreteStrategy (Minus, Plus ) - implements the algorithm using the Strategy interface
  • Context (CalculateClient) - is configured with a ConcreteStrategy object; maintains a reference to a Strategy object and may define an interface that lets Strategy access it's data.
UML

strategy.gif

C# Code Snippet
  1. /* Select the strategy and execute 
  2. Here the strategies are Minus and Plus 
  3. */  
  4.    class MainApp  
  5. {  
  6.     static void Main()  
  7.     {  
  8.         CalculateClient minusClient = new CalculateClient(new Minus());  
  9.         Response.Write("Minus: " + minusClient.Calculate(7, 1).ToString());  
  10.   
  11.          CalculateClient plusClient = new CalculateClient(new Plus());  
  12.          Response.Write("Plus: " + plusClient.Calculate(7, 1).ToString());  
  13.          // Wait for user  
  14.         Console.ReadKey();  
  15.     }  
  16. }  
The interface for the strategies

  1. public interface ICalculateInterface  
  2. {  
  3.        //define method  
  4.   int Calculate(int value1, int value2);  
  5. }  

The 'ConcreteAggregate' classes

Strategy 1: Minus

  1. class Minus : ICalculateInterface  
  2. {  
  3.        public int Calculate(int value1, int value2)  
  4.         {  
  5.            //define logic  
  6.            return value1 - value2;  
  7.         }  
  8. }  
Strategy 2: Plus
  1. class Plus : ICalculateInterface  
  2. {  
  3.        public int Calculate(int value1, int value2)  
  4.         {  
  5.            //define logic  
  6.            return value1 + value2;  
  7.         }  
  8. }  
The client
  1. class CalculateClient  
  2. {  
  3.        private ICalculateInterface calculateInterface;  
  4.   
  5.        //Constructor: assigns strategy to interface  
  6.        public CalculateClient(ICalculateInterface strategy)  
  7.         {  
  8.             calculateInterface = strategy;  
  9.         }  
  10.   
  11.         //Executes the strategy  
  12.        public int Calculate(int value1, int value2)  
  13.         {  
  14.            return calculateInterface.Calculate(value1, value2);  
  15.         }  
  16. }  
Output

Minus: 6
Plus: 8