Strategy
Category
Behavioral pattern
Problem
Define a family of algorithms, put each one in a separate class, and make them interchangeable at runtime. Useful when you have multiple algorithms for a task and need to switch between them dynamically.
Solution
- Define a Strategy interface with a method for each algorithm
- Create ConcreteStrategy classes, each implementing one algorithm
- The Context holds a reference to a Strategy and delegates to it
- The strategy can be swapped at runtime without changing the Context
Structure
- Strategy: Interface declaring the algorithm method
- ConcreteStrategy: Implements the algorithm
- Context: Uses the Strategy; can accept a new strategy at runtime
Key Benefits
- Swappable algorithms — Switch algorithms at runtime without changing client code
- Eliminates conditionals — No need for switch/if-else chains selecting algorithms
- Open/Closed Principle — New strategies can be added without modifying the Context
Trade-offs
- Client must understand differences — Client needs to know which strategy to choose
- More objects — Each algorithm becomes a separate class
When to Use
- Many related classes differ only in their behavior
- You need to switch algorithms at runtime
- You want to hide algorithm complexity from clients
- Algorithms are related but have different implementations
Examples
- Java
- Payment processing (credit card, PayPal, Stripe as interchangeable strategies)
- Sorting algorithms (quick sort, merge sort, bubble sort as strategies)