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