19

Chain of Responsibility and Iterator: approvals and manifests

A shipment-approval chain that stops at the first handler, and a manifest traversed by a hand-written iterator and a stream.

Demo 19Source on GitHub ↗

Two patterns about passing work along and walking a structure. Chain of Responsibility sends an approval request down a line of handlers until one takes it, shown as an object chain and as a functional composition of Function<Request, Optional<Outcome>> resolved with Stream.flatMap(Optional::stream).findFirst(). Iterator gives a ShipmentManifest an Iterable implementation with a hand-written zone-order iterator, plus a stream, and explains why you rarely hand-write an iterator now.

The JUnit 5 tests prove the chain routes to the correct handler and falls back when none takes the request, and that the iterator and stream traverse in the same order.

Build, run, observe

cd examples/19-chain-iterator
mvn -q test
./demo.sh

The module also runs from the aggregator root with mvn -q -f examples/pom.xml test.