All topics
library
intermediate

Strategy Pattern with Functional Interfaces

Replace class-based strategy implementations with lambdas and functional interfaces for cleaner code.

The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. In pre-Java 8, this required separate classes for each strategy. With lambdas and functional interfaces, strategies become one-liners.

Strategy = GPS navigation modes. The destination (context) stays the same, but you can switch between 'fastest route,' 'shortest route,' or 'avoid tolls' (strategies) without changing the map app.

Key Concepts

1
Traditional approach: 1. Define a Strategy interface with one method 2. Create concrete classes for each strategy 3. Pass the strategy to the context class
2
Modern approach (Java 8+): 1. Use an existing functional interface (Predicate, Function, Comparator) or define a @FunctionalInterface 2. Pass lambdas directly — no need for separate classes 3. Store strategies in a Map for registry pattern
3
Common JDK examples: - Comparator: Collections.sort(list, (a, b) -> a.length() - b.length()) - Predicate: list.stream().filter(s -> s.startsWith("A")) - Function: list.stream().map(String::toUpperCase)
4
Strategy + Map = dispatch table: replace long if-else/switch chains with a Map<String, Function<Input, Output>>. Add new strategies without modifying existing code (Open/Closed Principle).