Strategy pattern is used when we have multiple algorithms for a specific task and client decides the actual implementation need to be used at runtime.
The strategy pattern defines multiple algorithms/classes, encapsulates each algorithm, and makes the algorithms interchangeable within that family. Strategy lets the algorithm vary independently from clients that use it.
To make the algorithms interchangeable, client application passes the algorithm to be used as a parameter.
Collections.sort() method that takes Comparator parameter. The list can be sorted in different ways using different implementations of Comparator interfaces.
Elements Strategy Pattern
It is a Common Interface that implemented by to all supported algorithms (ConcreteStrategy).
ConcreteStrategy (BuubleSort, QuickSort, MergeSort)
This class implements the algorithm using the SortStrategy interface.
It maintains a reference to a Strategy object and logic to use the Strategy object.
What problems can the Strategy design pattern solve?
1. A class should be configured with an algorithm instead of implementing an algorithm directly.
2. An algorithm should be selected and exchanged at run-time.
What is an algorithm?
An algorithm is a procedure that takes some value as input, performs a finite number of steps, and produces some value as output. From a more general perspective, an algorithm is a piece of code that does something appropriate.
Implementing an algorithm directly within the class that uses the algorithm is inflexible because it commits the class to a particular algorithm at compile-time and makes it impossible to change the algorithm later independently from (without having to change) the class. This also stops the class from being reusable when another algorithm should be used.
What solution does the Strategy design pattern describe?
1. Define a separate (strategy) object that encapsulates an algorithm.
2. A class delegates an algorithm to a strategy object at run-time instead of implementing an algorithm directly (that is, instead of committing to an algorithm at compile-time).
Strategy pattern use in Java Libraries?
1. java.util.Comparator#compare(), executed by among others Collections#sort().
2. javax.servlet.http.HttpServlet, the service() and all doXXX() methods take HttpServletRequest and HttpServletResponse and the implementor has to process them.