17
Composite, Flyweight, and Null Object
A palletizing model with a recursive package tree, a shared SKU-descriptor pool, and a do-nothing exception handler.
A palletizing model that combines three structural ideas:
- Composite. A
PackageComponentinterface with anItemleaf and aPackageGroupcomposite (one class used as both carton and pallet), sototal_weight()anditem_count()recurse uniformly over a mixed, multi-level tree. - Flyweight. A
SkuCatalogpool hands out sharedshared_ptr<const SkuDescriptor>flyweights; many line items reference a few descriptors, andpool_size()proves growth stays bounded. - Null Object. A
NullShipmentExceptionHandlerlets client code call a handler unconditionally instead of branching on null.
The C++23 codetabs path uses std::flat_map for the pool (vs std::map in
C++20), plus a guarded try_get() returning std::expected.
Build, run, observe
./scripts/build.sh cpp23
./scripts/verify.sh cpp23 # 18/18 tests pass
./examples/17-composite-flyweight/demo.sh cpp23
The demo totals a nested pallet, shows the flyweight pool staying small as line
items grow, and routes an exception through the null and logging handlers.
Chapter 17 covers when each pattern fits. Builds standalone and under the
cpp20 preset (16 tests).