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.
Code
- using System;
-
- namespace Patterns
- {
- class Program
- {
- static void Main(string[] args)
- {
- Calc _Calc = new Calc();
- _Calc.SetStrategy(new Add());
- _Calc.ShowOutput(10, 20);
-
-
- _Calc.SetStrategy(new Mul());
- _Calc.ShowOutput(10, 20);
-
- }
- }
-
- interface IStrategy
- {
- int Calculate(int FirstNumber, int SecondNumber);
- }
-
- class Add : IStrategy
- {
- public int Calculate(int FirstNumber, int SecondNumber)
- {
- return FirstNumber + SecondNumber;
- }
- }
- class Mul : IStrategy
- {
- public int Calculate(int FirstNumber, int SecondNumber)
- {
- return FirstNumber * SecondNumber;
- }
- }
-
- class Calc
- {
- IStrategy _Strategy;
- public void SetStrategy(IStrategy Strategy)
- {
- _Strategy = Strategy;
- }
- public void ShowOutput(int FirstNumber, int SecondNumber)
- {
- Console.WriteLine(_Strategy.Calculate(FirstNumber, SecondNumber));
- Console.ReadLine();
- }
- }
- }