Define a family of algorithms and make them interchangeable. You need runtime selection of behavior. You want to avoid large switch statemen
Strategy
Overview
Define a family of algorithms and make them interchangeable.
When to use
- You need runtime selection of behavior.
- You want to avoid large switch statements.
Java example
TypeScript example
Pros and cons
Pros:
- Replaces complex conditional logic.
- Easy to add new strategies.
Cons:
- More classes or functions to manage.
- Clients must choose a strategy.
Common pitfalls
- Strategies with overlapping responsibilities.
- Hard-coded strategy selection in many places.