☕ Java Advanced

What is the Strategy design pattern in Java?

Answer

The Strategy pattern defines a family of algorithms, encapsulates each one as a class implementing a common interface, and makes them interchangeable. The client selects the algorithm at runtime without changing the code that uses it. Example: a Sorter class with a SortStrategy interface — you can swap between BubbleSortStrategy and QuickSortStrategy without changing Sorter. In modern Java, strategies are often just lambdas or method references since they are instances of functional interfaces. The pattern promotes the Open/Closed Principle (open for extension, closed for modification) and is used extensively: Collections.sort(list, comparator) is the Strategy pattern with Comparator as the strategy.