Strategy Design Pattern With Implmentation

Strategy is a plan to achieve some goal. Let's see what Strategy design pattern says :

Strategy is a Behavioral type of design pattern.

Behavioral Design Pattern

It's about object communication, their responsibilities and how they communicate with each other.

The strategy pattern is a group of similar algorithms to be defined. The algorithm to be used for a particular requirement may then be called at run-time.

I will try to explain this pattern through an example,

Here we have an Employee class which has 3 properties: Name, Address and EmployeeDepartment . We want to get the bonus of employee and the calculation is done based on the department the Employee belongs to. In real time there will be some complex logic to calculate the bonus, for example purposes I am just returning some values.

We have a class EmployeeBonusCalculatorService which has a Method Calculate bonus. Calculate Bonus takes the Employee object as parameter and based on Employee type(switch case), it calls the respective Bonus calculation methods.

  1. public class Address {  
  2.     public string ContactName {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public string AddressLine1 {  
  7.         get;  
  8.         set;  
  9.     }  
  10.     public string AddressLine2 {  
  11.         get;  
  12.         set;  
  13.     }  
  14.     public string AddressLine3 {  
  15.         get;  
  16.         set;  
  17.     }  
  18.     public string City {  
  19.         get;  
  20.         set;  
  21.     }  
  22.     public string State {  
  23.         get;  
  24.         set;  
  25.     }  
  26.     public string Country {  
  27.         get;  
  28.         set;  
  29.     }  
  30.     public string PostalCode {  
  31.         get;  
  32.         set;  
  33.     }  
  34. }  
  35. public enum EmployeeDepartment {  
  36.     Sales,  
  37.     IT,  
  38.     Finance  
  39. }  
  40. public class Employee {  
  41.     public string Name {  
  42.         get;  
  43.         set;  
  44.     }  
  45.     public Address Address {  
  46.         get;  
  47.         set;  
  48.     }  
  49.     public EmployeeDepartment EmployeeDepartment {  
  50.         get;  
  51.         set;  
  52.     }  
  53. }  
  54. public class EmployeeBonusCalculatorService {  
  55.     public int CalculateBonus(Employee employee) {  
  56.         switch (employee.EmployeeDepartment) {  
  57.             case EmployeeDepartment.Finance:  
  58.                 return CalculateBonusForFinance(employee);  
  59.             case EmployeeDepartment.IT:  
  60.                 return CalculateBonusForIT(employee);  
  61.             case EmployeeDepartment.Sales:  
  62.                 return CalculateBonusForSales(employee);  
  63.             default:  
  64.                 throw new Exception("Unknown Error");  
  65.         }  
  66.     }  
  67.     private int CalculateBonusForSales(Employee employee) {  
  68.         return 300;  
  69.     }  
  70.     private int CalculateBonusForIT(Employee employee) {  
  71.         return 500;  
  72.     }  
  73.     private int CalculateBonusForFinance(Employee employee) {  
  74.         return 400;  
  75.     }  
  76. }  

Run the console application with

  1. class Program {  
  2.     static void Main(string[] args) {  
  3.         EmployeeBonusCalculatorService _service = new StrategyPattern.EmployeeBonusCalculatorService();  
  4.         int bonus = _service.CalculateBonus(new StrategyPattern.Employee {  
  5.             Name = "Max",  
  6.                 Address = new Address {  
  7.                     ContactName = "Marry",  
  8.                         AddressLine1 = "302 Nagrajan Building",  
  9.                         AddressLine2 = "Kadugudi",  
  10.                         AddressLine3 = "Near Devi Temple",  
  11.                         City = "Bangalore",  
  12.                         State = "Karnataka",  
  13.                         PostalCode = "560076",  
  14.                         Country = "India"  
  15.                 },  
  16.                 EmployeeDepartment = EmployeeDepartment.Finance  
  17.         });  
  18.         Console.WriteLine(bonus);  
  19.     }  
  20. }  

Output would be : 400

Run the program with different EmployeeBBrect response.

Did you find any problem in the above code ?

Actually, this code will always give correct response but this code has a major design flaw.

Let's assume one more department is added, to accommodate new department what will we have to do ?

We'll have to modify our class EmployeeBonusCalculatorService and add 1 more switch case along with respective BonusCalculation Method which is breaking an Open/Closed Principle of SOLID principle which states that Entities should be open for extension but closed for modification. Also EmployeeBonusCalculatorService accomodating the logic of different Employee Departments which is breaking Single Responsibility Principle. Another principle that is breaking with the above design is "Change is one class is causing change in another class" If you remove or add any department type you need to come back to your service class and change the code accordingly. If you need to change one part of your system because of a change in another part of the sytem, it means system is tightly coupled.

Solution

Create separate Strategy class for each Department Type and each strategy should implement a common interface IDepartmentStrategy.

  1. public interface IDepartmentStrategy {  
  2.     int CalculateBonus(Employee emp);  
  3. }  

I have modified Employee class a bit and removed property EmployeeDepartment from it, may or may not be present (depends on domain experts, I have just removed as after design change it won't be required anymore)

  1. public class Employee {  
  2.     public string Name {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public Address Address {  
  7.         get;  
  8.         set;  
  9.     }  
  10. }  
  11. //Strategy Implentation  
  12. public class FinanceStrategy: IDepartmentStrategy {  
  13.     public int CalculateBonus(Employee emp) {  
  14.         return 400;  
  15.     }  
  16. }  
  17. public class SalesStrategy: IDepartmentStrategy {  
  18.     public int CalculateBonus(Employee emp) {  
  19.         return 300;  
  20.     }  
  21. }  
  22. public class ITStrategy: IDepartmentStrategy {  
  23.     public int CalculateBonus(Employee emp) {  
  24.         return 500;  
  25.     }  
  26. }  
  27. //Modify Service Class  
  28. public class EmployeeBonusCalculator_With_Strategy_Service {  
  29.     IDepartmentStrategy _departmentStrategy;  
  30.     public EmployeeBonusCalculator_With_Strategy_Service(IDepartmentStrategy departmentStrategy) {  
  31.         _departmentStrategy = departmentStrategy;  
  32.     }  
  33.     public int CalculateBonus(Employee employee) {  
  34.         return _departmentStrategy.CalculateBonus(employee);  
  35.     }  
  36.     Call from Main method  
  37.     class Program {  
  38.         static void Main(string[] args) {  
  39.             IDepartmentStrategy strategy = new FinanceStrategy();  
  40.             EmployeeBonusCalculator_With_Strategy_Service _service = new StrategyPattern.EmployeeBonusCalculator_With_Strategy_Service(strategy);  
  41.             int bonus = _service.CalculateBonus(new StrategyPattern.Employee {  
  42.                 Name = "Max",  
  43.                     Address = new Address {  
  44.                         ContactName = "Marry",  
  45.                             AddressLine1 = "302 Nagrajan Building",  
  46.                             AddressLine2 = "Kadugudi",  
  47.                             AddressLine3 = "Near Devi Temple",  
  48.                             City = "Bangalore",  
  49.                             Region = "Karnataka",  
  50.                             PostalCode = "560076",  
  51.                             Country = "India"  
  52.                     }  
  53.             });  
  54.             Console.WriteLine(bonus);  
  55.         }  
  56.     }  

Output: Same 400

Now Add another Department type

  1. public enum EmployeeDepartment {  
  2.     Sales,  
  3.     IT,  
  4.     Finance,  
  5.     HR  

Add corresponding Strategy

  1. public class HRStrategy: IDepartmentStrategy {  
  2.     public int CalculateBonus(Employee emp) {  
  3.         return 600;  
  4.     }  

Now, no need to modify Service Class Just call Program -> Main method

  1. class Program {  
  2.     static void Main(string[] args) {  
  3.         IDepartmentStrategy strategy = new HRStrategy();  
  4.         EmployeeBonusCalculator_With_Strategy_Service _service = new StrategyPattern.EmployeeBonusCalculator_With_Strategy_Service(strategy);  
  5.         int bonus = _service.CalculateBonus(new StrategyPattern.Employee {  
  6.             Name = "Max",  
  7.                 Address = new Address {  
  8.                     ContactName = "Marry",  
  9.                         AddressLine1 = "302 Nagrajan Building",  
  10.                         AddressLine2 = "Kadugudi",  
  11.                         AddressLine3 = "Near Devi Temple",  
  12.                         City = "Bangalore",  
  13.                         Region = "Karnataka",  
  14.                         PostalCode = "560076",  
  15.                         Country = "India"  
  16.                 }  
  17.         });  
  18.         Console.WriteLine(bonus);  
  19.     }  

Output:600

Another way to implement Strategy is,

Define strategy

  1. public class DepartmentStrategy {  
  2.     public Func < Employee, int > ITStrategy = delegate(Employee employee) {  
  3.         return 500;  
  4.     };  
  5.     public Func < Employee, int > SalesStrategy = delegate(Employee employee) {  
  6.         return 300;  
  7.     };  
  8.     public Func < Employee, int > FinanceStrategy = delegate(Employee employee) {  
  9.         return 400;  
  10.     };  

Modify service class as,

  1. public class EmployeeBonusCalculator_With_Strategy_Service {  
  2.     public int CalculateBonus(Employee employee, Func < Employee, int > departmentStrategy) {  
  3.         return departmentStrategy(employee);  
  4.     }  

Main Method of Program Class

  1. class Program {  
  2.     static void Main(string[] args) {  
  3.         EmployeeBonusCalculator_With_Strategy_Service _service = new StrategyPattern.EmployeeBonusCalculator_With_Strategy_Service();  
  4.         Employee emp = new StrategyPattern.Employee {  
  5.             Name = "Max",  
  6.                 Address = new Address {  
  7.                     ContactName = "Marry",  
  8.                         AddressLine1 = "302 Nagrajan Building",  
  9.                         AddressLine2 = "Kadugudi",  
  10.                         AddressLine3 = "Near Devi Temple",  
  11.                         City = "Bangalore",  
  12.                         Region = "Karnataka",  
  13.                         PostalCode = "560076",  
  14.                         Country = "India"  
  15.                 }  
  16.         };  
  17.         int bonus = _service.CalculateBonus(emp, new DepartmentStrategy().FinanceStrategy);  
  18.         Console.WriteLine(bonus);  
  19.     }  
  20. }  

Output:400

Ebook Download
View all
Learn
View all