Strategy: shipping-rate estimation
One shipment, three interchangeable rate strategies, priced identically and proven by JUnit 5.
A checkout needs to compute a delivery cost, and the rate rule depends on the
carrier. This demo models a small shipping domain (a Shipment with a weight, a
destination zone, and a declared value, priced in a Money value type) and
shows the Strategy pattern in three idiomatic Java expressions, all pricing an
identical shipment identically:
- Classic interface. A
RateStrategyinterface withFlatRateStrategy,WeightTieredRateStrategy, andDistanceRateStrategy, injected into aShippingRateCalculatorand swapped at runtime. - Functional interface with lambdas. The same contract used with lambdas and
method references, built by the
RateStrategiesfactories, withwithInsuranceSurcharge()composing a new strategy on top of an existing one. - Enum strategy. A
Carrierenum whose constants (GROUND,AIR_FLAT,FREIGHT_ZONE) each carry their own algorithm, the right fit when the set of strategies is closed and known at compile time.
The RateStrategy contract and the Shipment, Money, and RateQuote value
types are Java records, and the JUnit 5 suite proves all three expressions
produce the identical quote for the same inputs.
Build, run, observe
With the toolchain from the prerequisites chapter (JDK 25, Maven):
cd examples/08-strategy
mvn -q test # 33 tests pass
./demo.sh # prints all three expressions agreeing on the same quote
The module also runs from the aggregator at the repository root with
mvn -q -f examples/pom.xml test.