Which pattern is behind list.sort(Comparator.comparing(Person::getAge))?
Options
- Strategy: the algorithm is fixed; the comparison rule is passed in (Correct option)
- Singleton: only one comparator exists in the whole program
- Adapter: the list is converted to a different interface first
- State: the list changes its behavior as its state changes
Answer
Strategy: the sorting algorithm is fixed, but the comparison rule is a replaceable object (or lambda) passed in
Why
Strategy: define a family of interchangeable algorithms behind one interface and let the caller choose which to use.
Here Comparator is the strategy interface. Sorting stays the same; you pass a different comparator (by age, by name) and the behavior changes without modifying sort.
With Java 8 lambdas, a strategy is often just a lambda.
Remember
Strategy = swap behavior by passing an object/lambda.