Tuesday, 18 May 2021

Strategy Design Pattern in C#

Introduction

    Strategy design pattern enables to select one of the algorithms at run time. It is a behavior design       pattern and is based on Inheritance principle.
    
It deals with
    1. Multiple possible algorithms for a problem. Or When there is a family of algorithm for a problem. 
    2. Dynamically any algorithm can be selected based on certain input.




   Example

  1. In eCommerce application online payment system, there are multiple payment options
    • Cash on delivery
    • CreditCard
    • UPI 
    • Internet Banking etc.
    2. String Sorting 
    • Bubble Sort
    • Merge Sort
    • Quick Sort etc.
   3. A manufacturing company pays its employee on weekly basis. If amount is less than 2000 dollor, it it is paid in cash and employee sign on voucher against cash received. If amount is more than or equal to 2000 dollor it is paid by cheque.  
    In this scenario, payment can be implmented as Cash and Cheque. Amount is the factor which drive which payment option will be selected.

This design pattern is one of the most frequently used one.

Implementation


  public interface IStrategy
 {
  void Execute();
 }

public class StrategyA: IStrategy
{
public void Execute()
{
Console.WriteLine("This is implementation of StrategyA::Execute");
}
}

public class StrategyB: IStrategy
{
public void Execute()
{
Console.WriteLine("This is implementation of StrategyB::Execute");
}
}

 public class Context
{
    private IStrategy _strategyA, _strategyB;

    public Context()
   {
     _strategyA = new StrategyA();

                _strategyB= new StrategyB(); 

    }

    public void OperationA()
    {
        Console.WriteLine("Context OperationA method");
        _strategyA.Execute();
       _strategyB.Execute();

    }
}



Note: Most of the time Strategy is used along with factory. For real world example please write to me.