Strategy
Intent
Package each variant of one step behind a common interface so the caller can swap variants at runtime without rewriting its flow.
Motivation
A shop checkout totals an order the same way every time, but payment differs: card talks to a gateway, cash just opens a drawer, wallet calls a phone API. Branching inside the order code for each method grows brittle — every new method edits the same function and risks breaking the others. Strategy moves each payment into its own unit and lets the order hold whichever one is selected.
Structure
flowchart LR Order[Order Context] --> Pay[PayMethod Strategy] Pay --> CardPay[Card Payment] Pay --> CashPay[Cash Payment] Pay --> WalletPay[Wallet Payment]
- Context (Order) — owns the flow and the currently chosen method; delegates the pay step.
- Strategy (PayMethod) — the shared payment step contract.
- Concrete strategies — CardPay, CashPay, WalletPay with distinct steps.
Consequences
- Benefit: new methods plug in without editing order flow; each method stays testable alone.
- Cost: more small units to discover; caller must still choose correctly, which can push selection logic elsewhere.
Basic Recap
Strategy encapsulates interchangeable algorithms behind one contract and lets a context delegate the varying step. Selection occurs through configuration, request attributes, or composition rather than a growing conditional inside the workflow. Each strategy should honor compatible inputs, outputs, and failure semantics. The pattern separates algorithm choice from orchestration, but it does not decide which choice is safe for a given situation.
Complex Scenario
A distributed API gateway enforces request limits using fixed-window,
sliding-window, and token-bucket strategies behind a LimitAlgorithm interface.
The limiter context loads a client’s current state, delegates the decision, and
returns a common allow-or-throttle result with retry metadata. Administrators
select an algorithm per route without modifying request handling. Shared state
storage and concurrency requirements are part of the strategy contract, not an
afterthought hidden in each implementation.
Edge cases
- Concurrency: Simultaneous requests can all pass if read-modify-write state updates are not atomic, even though each strategy works in a single-threaded test.
- Retries: A client retry is another request and normally consumes budget; internal gateway retries need a clear rule about whether they re-enter the strategy.
- Partial failure: If the shared state store is unavailable, the context must apply a route-specific fail-open or fail-closed policy and report degraded enforcement.
- Memory pressure: High-cardinality client keys require expiry and bounded local caches regardless of the chosen algorithm.
Strategies may return different diagnostic details, but the context must normalize them without weakening the common decision contract.
Sketch (illustrative pseudocode, not runnable):
RateLimiter.check(request):
policy = policies.forRoute(request.route)
key = policy.clientKey(request)
result = policy.algorithm.consumeAtomically(key, request.cost, clock.now)
return Decision(result.allowed, result.retryAfter, policy.name)
Gateway.handle(request):
try:
decision = limiter.check(request)
except StateStoreUnavailable:
decision = degradedDecisionFor(request.route)
return forward(request) if decision.allowed else throttle(decision)
When to Use / When Not to Use
Use when:
- Multiple variants of one step swap at runtime or per configuration.
- You want to test each variant without running the whole flow.
Avoid when:
- Only one variant exists and none is foreseen, or variants differ in flow shape rather than one step.
Examples
examples/elixir/strategy/examples/dart/strategy/examples/go/strategy/examples/rust/strategy/
Expected outcome: paying $100 by card then by cash prints two distinct lines with the same total.
Anti-pattern / Failure Mode
-
Misuse: A strategy interface with one implementation and no expected variants.
-
Review signal: Callers switching on type tags instead of injecting the variant.
-
Misuse symptom: Strategies have subtly incompatible contracts, and the context grows type checks to compensate for different result shapes or state requirements. Introducing separate strategy classes for trivial one-line branches can also obscure behavior without enabling real interchange.
-
Review signal: Look for selection strings scattered through request code, algorithms with different retry or atomicity assumptions, and tests that never exercise strategies under contention. A configurable strategy name accepted without validation can turn a small extension point into an unsafe runtime dependency lookup.
Related
- State — caller picks vs object transitions.
- Template Method — inject the step vs subclass it.
- Order Pipeline — strategies isolate payment variants.
Exercise
Add a wallet method that charges a $1 fee. Total must still print $101 for wallet and $100 for others. Do not edit the order flow file beyond registering the new method.
Self-check
- Who owns variant selection?
Answer
The caller/Context wiring, not the strategies — strategies only execute. - Strategy vs if-else: what changed?
Answer
Branching moved from inline conditionals to polymorphic delegation; adding a method adds a unit instead of editing a function. - When would State fit better?
Answer
When the object itself changes behavior as its internal status evolves, not when the caller picks a method.