Properties:
- Separates implementation from algorithm (strategy).
- The same class can be used with different algorithms.
Implementation:
- Strategy creates an abstraction for different algorithms.
- ConcreteStrategy implements strategy interface for a specific algorithm.
- Context object uses strategy object to do its job. Its behaviour depends on the concrete strategy implementation.
Java Standard Library Implementations:
- java.util.Collections.html#sort(java.util.List, java.util.Comparator) uses Comparator as strategy.
Example Usage:
List<Person> winners = ...
// Strategy instance
Comparator<Person> comparator = new Comparator<Person>() {
public int compare(Person o1, Person o2) {
return o1.getAge() - o2.getAge();
}};
// Set strategy
Collections.sort(winners, comparator);
Comments
Post a Comment