SteelReed

Search

Search posts, questions…

OOP & DesignQuestion 24 / 42

Junior

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.

Spring injects list ofStrategyRegistry: Map by keyduplicates checked atstartupRequest: carrier GHNGHN strategyShipping fee

3 points to say:

  1. Strategy = interchangeable algorithms behind one interface, replacing if/else by type.
  2. Spring: List<Strategy> → Map by key, duplicates checked at startup; one single place chooses, no scattered switch.
  3. 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.