Strategy Pattern In C#

Strategy pattern is a behavioral pattern. “It defines a family of algorithms, encapsulate and make them interchangeable.”  We need to let the algorithm vary independently from the client that uses it.

For example: During program execution, we may need to change the flow of execution, based on some status or Workflow state. In this case, one solution is,  we can add the conditional statements and handle our logic in each state.

Otherwise, we can implement strategy pattern.

Let’s take a real life example of a Football game, where a team can change its strategy any time during the Football game.

diagram

Code

  1. using System;  
  2.   
  3. namespace Patterns  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             Calc _Calc = new Calc();  
  10.             _Calc.SetStrategy(new Add());  
  11.             _Calc.ShowOutput(10, 20);  
  12.             //Output: 30  
  13.   
  14.             _Calc.SetStrategy(new Mul());  
  15.             _Calc.ShowOutput(10, 20);  
  16.             //Output: 200  
  17.         }  
  18.     }  
  19.   
  20.     interface IStrategy  
  21.     {  
  22.         int Calculate(int FirstNumber, int SecondNumber);  
  23.     }  
  24.   
  25.     class Add : IStrategy  
  26.     {  
  27.         public int Calculate(int FirstNumber, int SecondNumber)  
  28.         {  
  29.             return FirstNumber + SecondNumber;  
  30.         }  
  31.     }  
  32.     class Mul : IStrategy  
  33.     {  
  34.         public int Calculate(int FirstNumber, int SecondNumber)  
  35.         {  
  36.             return FirstNumber * SecondNumber;  
  37.         }  
  38.     }  
  39.   
  40.     class Calc  
  41.     {  
  42.         IStrategy _Strategy;  
  43.         public void SetStrategy(IStrategy Strategy)  
  44.         {  
  45.             _Strategy = Strategy;  
  46.         }  
  47.         public void ShowOutput(int FirstNumber, int SecondNumber)  
  48.         {  
  49.             Console.WriteLine(_Strategy.Calculate(FirstNumber, SecondNumber));  
  50.             Console.ReadLine();  
  51.         }  
  52.     }