intermediate
Strategy
Select interchangeable algorithms through a stable interface when policy varies independently from the caller workflow.
Strategy encapsulates interchangeable algorithms behind a common interface so the caller workflow stays stable while policy varies—pricing rules, sorting, compression, fraud scoring, or export formats. Selection can happen at runtime via configuration or dependency injection.
On interviews: contrast Strategy with Template Method and with simple function parameters. Explain testing each strategy in isolation.
Common pitfalls: strategies that secretly depend on global state; enum switches reintroduced beside strategy map; choosing Strategy for one-off conditionals.
The trade-off is flexibility versus complexity—know when the simpler path is enough.
Checklist:
- Caller depends on strategy interface only.
- Each strategy is independently unit tested.
- Registration or DI selects implementation.
- Document strategy selection precedence.