Repaso
Español
Design & PracticesIntermediateDP-45

Which pattern is behind list.sort(Comparator.comparing(Person::getAge))?

Options

  1. Strategy: the algorithm is fixed; the comparison rule is passed in (Correct option)
  2. Singleton: only one comparator exists in the whole program
  3. Adapter: the list is converted to a different interface first
  4. 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.

Key terms

Practice this question in Repaso