Strategy
Defines a family of algorithms, encapsulates each one, and makes them interchangeable so the algorithm can vary independently from the clients that use it.
errorWhat Problem Does the Strategy Pattern Solve?
When a class must support multiple variations of an algorithm, embedding all variants via conditionals bloats the class and violates the Open/Closed Principle. Adding a new algorithm requires modifying the class, and the algorithm cannot be reused across different contexts.
check_circleHow the Strategy Pattern Works
Extract each algorithm into its own class implementing a common Strategy interface. The Context holds a reference to a Strategy and delegates the work to it. At runtime—or via configuration—the concrete strategy can be swapped without touching the context or any other strategy.
Strategy Pattern Architecture
Rendering diagram...
Implementation by Language
Strategy Pattern in the Real World
“Consider a GPS app offering route options: fastest, shortest, or avoid tolls. The destination is the same, but the navigation algorithm changes based on your preference. The app (context) simply hands the journey off to whichever routing strategy you selected; you can switch strategies mid-trip without the app needing to change its structure.”
Frequently Asked Questions
helpWhat is the difference between Strategy and State patterns?
Strategy lets you swap algorithms from outside — the client chooses which strategy to use. State changes behavior from inside — the object switches its own state based on internal conditions. Strategy is 'choose how to do it'; State is 'behavior changes as I change'.
helpCan I use functions instead of classes for the Strategy pattern?
Absolutely. In languages with first-class functions (TypeScript, Python, JavaScript), passing a function is often simpler than creating a strategy class. Use classes when strategies need multiple methods, carry state, or require dependency injection.
How the Strategy Pattern Relates to Other Patterns
The Strategy pattern works well with the Factory Method to select algorithms at runtime. It is closely related to the State pattern — while Strategy swaps behavior explicitly, State transitions happen internally based on context.