What is the Strategy pattern, and how do you pick a strategy per request in Spring?
Short answer
Strategy wraps each interchangeable algorithm behind a common interface, so the caller needs no if/else by type (GHN vs GHTK shipping fees, discounts by voucher type). In Spring, each strategy is a bean, picked through a registry by key.
3 points to say:
- Strategy = interchangeable algorithms behind one interface, replacing
if/elseby type. - Spring:
List<Strategy>→Mapby key, duplicates checked at startup; one single place chooses, no scatteredswitch. - A strategy is a singleton bean, so it must be stateless; for a small fixed set an enum with methods is enough.
Keep reading the deep dive
Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.