How much does the cargo bike weigh?
The freight company would not quote without the shipping weight of a bicycle maker's new cargo bike. Sales asked the product database, which had answered that question for every bike the company had built: 31.4 kg. The first bike off the line weighed 33.5 kg on the workshop scale.
A bike in that database is a bill of materials, a list of what it is made of. Some entries are parts bought as they are: a frame, a motor, a chain. Others are assemblies built in-house from other entries, such as the drive unit, which is a motor, a battery, a bracket and a controller. The weight function looped over the bike's entries, added each part's weight, and looped over each assembly's entries too. No earlier bike had an assembly inside an assembly, so two loops were enough. The cargo bike's controller, inside the drive unit, is itself an assembly of a processor module, a housing and a cable harness. The inner loop met it where it expected parts, had no branch for it, and added nothing. The controller's 2.1 kg was the missing weight.
One question every entry can answer
A third loop would have fixed this bike and waited for the first one a level deeper. The function asked every entry what it was because parts and assemblies had nothing in common it could ask. Give the single thing and the group one shared interface, so a client asks both the same question, and the design has a name, taken from the group that can stand wherever a single item can: Composite. Here the interface is BomItem, with weight() and cost(). A Part is a leaf: it has no children and answers from its own data. An Assembly is a composite: it holds a list of children and answers by asking each of them, adding up the results and adding its own contribution, such as the screws that hold it together or, for cost(), the labour of assembling it.
The list inside Assembly holds BomItems, not Parts, and that one type is what makes the pattern recursive. An assembly can contain parts, assemblies, or assemblies of assemblies, and neither its code nor the client's changes when the tree gets deeper.
Part and Assembly both implement BomItem, and an Assembly's children are BomItems, so a child can be a part or another assembly.
The sales report now calls weight() on the bike and nothing else. Follow the call down:
- The report calls
weight()on the cargo bike, which is an assembly. - The bike calls
weight()on each child: the frame, the cargo box, the wheels, the drive unit. - The frame is a part and returns its own weight.
- The drive unit is an assembly and does what the bike did, asking the motor, the battery, the bracket and the controller.
- The controller is an assembly too and asks its processor module, housing and harness, which are parts and return their weights.
- Each assembly returns the sum of its children plus its own screws, until the bike returns the total.
The recursion stops at parts, and at any assembly with no children, which simply returns its own contribution.
Part of one bike's entries at one moment: assemblies hold parts and other assemblies.
That second drawing shows instances, one bike as it is stored, not classes. Object diagrams: one moment of a running system shows how to test a concrete tree like this one against a class diagram like the first.
Where add() lives
Engineers also build the tree, in an editor where they drag a part into an assembly, and the editor needs add(item) and remove(item). Composite has no free answer to where those methods go.
Put them on BomItem, and every entry offers them. Clients see one interface for everything, which is called transparency. The price is that a Part asked to add a child can only refuse: throw an error, or return a failure the caller has to check. Even in a statically typed language, a call that adds a child to a part then compiles, and the refusal comes only when it runs.
Put them on Assembly only, and a part does not have them to be asked. That is safety. The price moves to the client: to add a child, the editor must know that it holds an Assembly, so it keeps that type when it opens one, or checks once what it was given before adding.
Either way, weight() and cost() stay on the shared interface, and code that only calls those two never needs to know which kind of node it holds. The bike team chose safety, because only the editor adds children and it always knows when it has opened an assembly. A codebase where many clients build trees generically might reasonably choose transparency. What causes trouble is drifting between the two, with add on the interface for some kinds of entry and on a concrete class for others, so that every client has to look up what it may call.
Shared parts and loops
The same drive unit goes into three models, and storing it once as a child of all three bikes is fine while every operation only reads, since each bike counts its one drive unit once. It stops being a plain tree, though: a parent field on the drive unit can no longer say which bike it belongs to, and an edit to it changes all three bikes at once, which is right when it really is one design and a surprise when an engineer meant to change one model. When many leaves carry identical data, sharing that data between them is what Flyweight does.
weight() call recurses until the stack runs out. Before linking, add should check that the assembly receiving the child is neither the child itself nor anywhere inside it.Not the tree's job
Walking the tree in a chosen order, such as printing the bill of materials as an indented list, can be left to Iterator, and a growing list of operations over parts and assemblies (an export to purchasing, a battery report) can move out into a Visitor, so that neither becomes one more method on both classes. A Decorator shares the interface of what it holds too, but wraps exactly one object to add behaviour, where a composite holds any number of children and combines their answers.
The edge that makes it recursive
In the Composite Pattern Challenge, draw the classes rather than one bike: a Port / Interface node for BomItem, a Composite node for Assembly, and two or three leaves as Component nodes, each of them and Assembly with an edge to the interface it implements. The edge that makes the pattern is the one from Assembly back to BomItem, its children. Point it at a leaf instead and you have drawn the bug from the workshop scale: an assembly that can hold parts but not assemblies. Then show your answer to the add() question in the card that carries it, with a title such as Assembly (add, remove), and check that every leaf still answers weight() without knowing what holds it. Iterator and Visitor are in the palette; add one only for a job named in the section above.