Composite

Term side of the Card.
Topic: Structural Patterns
Unit title: Composite
Categories: Design pattern
Explanation side of the Card

Explanation: 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.

Example

Wrongjs
function size(node) {
  if (node.type === 'file') return node.bytes;
  return node.children.reduce((sum, c) => sum + c.bytes, 0);
}
Rightjs
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.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy