Composite
Example
function size(node) {
if (node.type === 'file') return node.bytes;
return node.children.reduce((sum, c) => sum + c.bytes, 0);
}function size(node) {
if (node.type === 'file') return node.bytes;
return node.children.reduce((sum, c) => sum + size(c), 0);
}Recursing into each child treats files and folders the same, so sizes are correct at any nesting depth.
Common mistakes
- Handling only direct children, so nested folders or menus are skipped.
- Type checks in every caller instead of one shared interface.
Key points
- Leaves and containers expose the same methods, so callers don't check the node type.
- Operations on a container recurse into children of any depth, not just one level.
Interview questions
What are real examples of the Composite pattern?
File systems with files and folders, nested menus, UI component trees, the DOM and organization charts.
Composite vs Decorator: what is the difference?
Both build object structures. A Composite groups many children into a tree; a Decorator wraps exactly one object to add behavior.
Is the DOM an example of the Composite pattern?
Yes. Elements and text nodes share the Node interface, and an element can contain other nodes to any depth.