Can you give a concrete example of the Strategy pattern already built into the Java standard library?
java.util.Comparator, used with List.sort(Comparator) or Collections.sort(list, comparator), is a textbook example. The sorting algorithm behind the scenes stays completely fixed — the JDK doesn't rewrite its sort implementation for every different ordering you might want. What varies is the comparison logic that decides which of two elements should come first, and that logic is fully swappable: pass a comparator that orders by name, pass a different one that orders by date, and the same sort() call produces different results without any change to the sorting algorithm itself. This is exactly the Strategy shape — a fixed context (the sort operation) delegating to an interchangeable, caller-supplied algorithm (the comparison logic) behind a single-method interface.
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response