design patterns ·
Strategy
Defines a family of algorithms, encapsulates each one, and makes them interchangeable at runtime.
Theory
Explanation
Intuition first, formal definition second. Skim the bullets if you already know this; read the prose if you don't.
When a class needs to use one of several algorithms and you want to switch between them without if/else chains, extract each algorithm into its own Strategy class and inject the desired one into the Context.
Context holds a reference to a Strategy interface. Client sets the concrete Strategy. Context delegates algorithm execution to the Strategy. Context and Strategy interact through the Strategy interface only.
When to use
Sorting algorithms, payment methods (credit card/PayPal/crypto), compression/encryption strategies, navigation routing, validation rules, pricing strategies.
When not to
When there is only one algorithm or it never changes. When the algorithms differ only in a parameter - a single method with parameters is simpler.
Key insights
- Strategy is behavioral (algorithm selection) while Bridge is structural (implementation separation)
- State pattern is similar but State transitions automatically; Strategy is set by the client
- Java Comparator is Strategy - passed to sort() to define the comparison algorithm
- Lambdas can replace Strategy classes for single-method strategies in Java 8+