design patterns · behavioral
Strategy
Defines a family of algorithms, encapsulates each one, and makes them interchangeable at runtime.
Pattern
Overview
Intent
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
Real-World Analogy
A navigation app - same route request, different algorithms: fastest route, shortest route, avoid tolls, avoid highways.
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.
Participants
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+