Notes
The problem
A warehouse needs the total weight of a shipment to quote a delivery fee. The naive client checks the type of each thing. If it is a box, it adds the box's own weight and loops over the contents. If it is an item, it returns the grams. Now repeat that walk for price, for item count and for the packing list. Every feature copies the type checks, and a new kind of container breaks all of them.
int weight(Object thing) {
if (thing instanceof NaiveBox b) {
int sum = b.tare;
for (Object o : b.contents)
sum += weight(o);
return sum;
}
if (thing instanceof NaiveItem i)
return i.grams;
throw new IllegalArgumentException();
} The idea
The idea: give single items and groups the same interface. A group holds children of that same interface, and answers any question by asking its children and combining their answers. More formally, composite arranges objects into tree structures that represent part and whole hierarchies, and lets clients treat individual objects and compositions of objects uniformly. The client never needs to ask which one are you.
- give single items and groups
- the SAME interface
- a group holds children of
- that interface and answers
- by asking its children
- the client never asks
- "which one are you?"
The roles
Four roles with our names. The component is the shipment part interface, the type everyone talks to. The leaf is an article, a real product with a weight and a price and no children. The composite is a carton, which has its own empty weight and a list of shipment parts inside. Notice the link going back up: a carton contains components, so it can contain articles or other cartons. The shipping desk is the client.
Component and leaf
The component interface lists what every part can answer: a name, a weight in grams, a price and how many articles it holds. The leaf is a Java record. Its name, weight and price come straight from its fields, and its article count is simply one. The leaf is where the recursion stops, so leaf methods are always short and never loop.
interface ShipmentPart {
String name();
int weightGrams();
int price();
int articleCount();
}
record Article(String name,
int weightGrams, int price)
implements ShipmentPart {
public int articleCount() { return 1; } The composite
The carton keeps its own empty weight, called tare, and a list of children typed as the interface. Its weight is the tare plus the weight of each child. Its price is the sum of the children's prices, because an empty carton is free. Each child might be an article or another carton, and the carton does not care. If it is a carton, that call simply repeats the same logic one level down.
class Carton implements ShipmentPart {
private final int tareGrams;
private final List<ShipmentPart> kids;
public int weightGrams() {
int sum = tareGrams;
for (ShipmentPart p : kids)
sum += p.weightGrams();
return sum;
}
} A real tree
Here is one real shipment, order seventy seven. An outer carton weighing three hundred grams holds a desk lamp of twelve hundred grams and a small bulb kit carton. The bulb kit weighs one hundred grams empty and holds two bulbs of eighty grams each. Notice that the bulb kit is itself a carton, built with the same add method. The tree can be as deep as the warehouse needs.
Carton kit = new Carton("bulb-kit", 100)
.add(new Article("Bulb", 80, 60))
.add(new Article("Bulb", 80, 60));
Carton order = new Carton("order-77", 300)
.add(new Article("Desk lamp",
1200, 450))
.add(kit); One call
The desk asks the outer carton for its weight, exactly as it would ask a single article. The outer carton starts with three hundred and asks the lamp, which says twelve hundred. It asks the bulb kit, which starts with one hundred and asks both bulbs for eighty each, returning two hundred and sixty. The outer carton returns one thousand seven hundred and sixty grams, and the desk quotes a fee of ninety.
Safe vs transparent
Where should add and remove live? In the transparent design, they sit on the component interface, so the client treats everything identically, but an article must then throw an unsupported operation exception at runtime. In the safe design, which we use, only the carton has add and remove, so the compiler stops you adding to an article, but code that builds trees must know it holds a carton. Reading code stays uniform either way.
- transparent: add/remove on
- the component interface
- + client never casts
- - Article.add() must throw
- UnsupportedOperationException
- safe: add/remove only on
- the composite (our choice)
- + the compiler stops misuse
- - code that builds trees
- must know it has a Carton
Practical details
A few practical details. Guard against cycles: our add method refuses a carton that would end up inside itself, even several levels down, or every total would recurse forever. Parent links are optional but help with full paths and moving nodes. Very large trees can cache totals and clear the cache when something changes. In Java seventeen, a sealed interface can list the only two kinds of part, which makes the tree's shape explicit.
- cycles: a carton must not
- contain itself, even deep
- down: check in add()
- parent links: optional, help
- with paths and moving nodes
- caching: big trees may cache
- totals, clear on change
- deep trees: recursion depth
- may need an explicit stack
- Java 17: sealed interface
When to use it
Use composite when your data is genuinely a tree of parts and wholes, when clients should not care whether they hold one thing or many, and when operations naturally combine children: sum, maximum, render, or search. Avoid it for a flat list, where a plain collection is simpler. Also avoid it when leaves and groups share almost no operations. Forcing them behind one interface then creates many methods that make no sense on one side.
- use when:
- • data is a part-whole tree
- • clients should not care if
- they hold one or many
- • operations combine children
- (sum, max, render, search)
- avoid when:
- • the structure is flat
- • leaves and groups need very
- different operations
Everyday trees
Once you see it, composite is everywhere. A file system has files and folders, and a folder's size is the sum of its contents. A restaurant menu has dishes and sections with sub sections. An org chart has employees and departments, and the salary of a department rolls up. Product bundles can contain other bundles. User interfaces nest buttons inside panels, and maths expressions combine numbers into bigger expressions.
- file system: File + Folder
- restaurant menu: Dish +
- Section with sub-sections
- org chart: Employee +
- Department, total salary
- product bundles: price of a
- bundle of bundles
- UI: Button + Panel
- maths: Number + Expression
In Java
Java's user interface toolkits are built on composite. In AWT, the container class extends component and holds a list of components, so a panel can hold buttons and other panels. Swing builds on the same classes. In JavaFX, parent extends node, and groups and panes hold child nodes. When a window lays itself out or paints, it walks the tree in exactly the recursive way we just saw.
java.awt.Container extends Component // a Container holds Components, // and is one itself Swing: JPanel inside JPanel JavaFX: Parent extends Node, Group and Pane hold children layout and paint walk the tree
Neighbours
Composite and decorator look alike, because both are recursive: an object holds something of its own type. A decorator wraps exactly one object and adds behaviour to it. A composite holds many children and combines their answers. Composite also pairs well with other patterns. An iterator can walk the tree in depth first order, and a visitor adds new operations, like customs forms, without editing every node class.
- Decorator: also recursive,
- but ONE wrapped child and
- it ADDS behaviour
- Composite: MANY children and
- it COMBINES their answers
- works well with:
- Iterator: walk the tree
- Visitor: new operations
- without editing nodes
In LLD interviews
In interviews, design an in memory file system is the classic composite question: total size, find by name, and list a folder recursively. Food app menus, company hierarchies and expression evaluators use it too. Common mistakes: type checks left in the client, leaves carrying an empty children list for no reason, no cycle check, and returning the internal list so callers can change the tree behind the composite's back.
- design a file system:
- size, find, ls -R
- restaurant or food app menu
- company hierarchy, approvals
- expression evaluator
- mistakes:
- • instanceof checks in client
- • leaf with an empty list
- • no cycle check
- • returning the live list
Say it like this
How to say it, for a file system. Entry is the component interface, file is the leaf, and folder is the composite that holds a list of entries. Size on a folder sums its children, so callers never check types. I put add only on folder, the safe design, so the compiler prevents adding to a file, and add refuses a folder that would contain itself.
- "Entry is the component; File
- is the leaf, Folder is the
- composite holding a list of
- Entry. size() on a folder
- sums its children, so callers
- never check types. add() is
- only on Folder, the safe
- design, with a cycle check."