Strategy Design Pattern

This is kind of Behavioral Design Pattern(BDP) and as per the BDP definition, “Behavioral patterns describe how the objects behave when they interact with each other” and this design pattern is used when we have number of options to choose our strategy among available strategies.

Example: Lets say you have one List of Employees which you want to sort based on your demand. So the Employee class can implement Comparable interface and can sort employees and in this way we can only sort Employees based on the implementation of compareTo(…) method. To sort Employee list on some other attribute, you may need to change the implementation of compareTo(…) method. But this does not sound that much good idea to execute.

So to get rid of this, we can create different Comparators for Employee class and in those different Comparators you can implement compare(…)  method as per your requirement. Now you can use those Comparators to sort your List of Employees.

i.e. Say we want to sort our Employee List on name and salary basis. So we can create two different Comparators and then write something like below code.

EmployeeNameComparator nameComparator = new EmployeeNameComparator();
Collections.sort(list, nameComparator);

EmployeeSalaryComparator nameSalComparator = new EmployeeSalaryComparator();
Collections.sort(list, nameSalComparator);
So you noticed that, we have 2 different Strategies to achieve our goal.
Hope this clears your doubt!!

One thought on “Strategy Design Pattern

Comments are closed.