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)
classDiagram
direction LR
class PricingService {
<<Context>>
-Map~String, PricingStrategy~ strategies
+quote(PricingRequest request) Money
}
class PricingStrategy {
<<Strategy>>
+priceFor(PricingRequest request) Money
}
class MonthlyPricing {
<<ConcreteStrategy>>
}
class TenPackPricing {
<<ConcreteStrategy>>
}
class DropInPricing {
<<ConcreteStrategy>>
}
class StudentPricing {
<<ConcreteStrategy>>
}
PricingService o-- PricingStrategy
PricingStrategy <|.. MonthlyPricing
PricingStrategy <|.. TenPackPricing
PricingStrategy <|.. DropInPricing
PricingStrategy <|.. StudentPricingParticipants
- 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