Cheatsheet

Strategy

Intent

Move each variant of the same calculation into its own class, all behind a shared contract, so you can pick one (or add new ones) without touching the code that uses them.

Structure (UML)

Spring contextPricingControllerPricingService«i»PricingStrategydrop-in×10ten-packstudentAthlete30monthly

Participants

  • Context (PricingService), which receives the strategies and delegates to the right one
  • Strategy (PricingStrategy), the shared contract
  • ConcreteStrategy (MonthlyPricing, TenPackPricing, DropInPricing, StudentPricing), one class per plan

PricingService.java

private final Map<String, PricingStrategy> strategies;

public PricingService(Map<String, PricingStrategy> strategies) {
    this.strategies = strategies;
}

public Money quote(PricingRequest request) {
    var strategy = strategies.get(request.plan());
    if (strategy == null) {
        throw new UnknownPlanException(request.plan());
    }
    return strategy.priceFor(request);
}

Pros

  • Open/Closed, a new plan is a new class and working code stays untouched
  • No more conditionals, the switch is gone
  • Each strategy is tested on its own, with small tests and no dependencies

Cons

  • More classes, even if each one is tiny
  • The client has to know the keys (monthly, ten-pack…) to ask for the right strategy

← Strategy · Run it