# Composite

> The Composite design pattern allows composing objects into tree-like structures to represent part-whole hierarchies.

## What is the Composite design pattern?

The design pattern used to treat individual objects and compositions of objects uniformly. It allows objects to be combined into tree structures to represent hierarchies, such as files and directories.

- Topic: Structural Patterns
- Type: design pattern

## Example

Wrong:

```js
function size(node) {
  if (node.type === 'file') return node.bytes;
  return node.children.reduce((sum, c) => sum + c.bytes, 0);
}
```

Right:

```js
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.

## Related cards

- [Tree](https://wonderium.dev/algorithms/tree.md)
- [Recursion](https://wonderium.dev/algorithms/recursion.md)
- [Directory](https://wonderium.dev/engineering/directory.md)
- [Iterator](https://wonderium.dev/engineering/iterator.md)
- [Visitor](https://wonderium.dev/engineering/visitor.md)

---

- Level: [Engineering](https://wonderium.dev/engineering.md)
- HTML version: https://wonderium.dev/engineering/composite
- Last updated: 2026-11-25
