Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 57 ยท Structural Patterns

Composite

Learn the Composite design pattern: treat single objects and groups the same way through one interface, with a file system tree and recursion examples.

The Composite pattern lets you build a tree of objects and then treat the whole tree, a branch or a single leaf through the same interface. A client calls size() or render() on a node and does not care whether that node is one item or a container holding hundreds of items.

Trees are everywhere: folders that contain files and other folders, menus that contain items and submenus, a drawing where a group of shapes can itself be grouped, an HTML page of nested elements, an organization chart. Without Composite, the code that walks such a tree is full of checks like "is this a folder? then loop over its children, otherwise handle it directly". With Composite, that decision moves into the objects themselves.

One interface, two kinds of node

Leaf Does the real work. Has no children.
Composite Holds children and forwards each request to them.
Component The shared interface both of them implement.

The client only ever talks to the Component.

1 / 2

The structure

Three roles make up the pattern:

  • Component: the interface (or abstract class) that declares the operations common to simple and complex nodes, for example size().
  • Leaf: a node with no children. It implements the operation directly.
  • Composite: a node that stores child components. It implements the operation by asking each child to do it, then combining the answers.
classDiagram
    class FileSystemNode {
        <<interface>>
        +name
        +size()
    }
    class File {
        +size()
    }
    class Folder {
        -children
        +add(node)
        +size()
    }
    FileSystemNode <|.. File
    FileSystemNode <|.. Folder
    Folder o--> "0..*" FileSystemNode : children

A folder is a node that holds other nodes, which is why the tree can be nested to any depth.

The key line in the diagram is the arrow from Folder back to the interface, not to File. A folder's children are components, so a child can be a file or another folder. That one arrow is what makes the structure recursive.

A file system tree

The classic example is a small file system. A File knows its own size. A Folder has no size of its own: its size is the sum of its children. Notice that Folder.size() never asks whether a child is a file or a folder.

JS Sizes and listings through one interface

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The same call, size(), works on the whole project, on the src branch and on one file. The empty folder correctly reports 0 because summing no children gives 0.

Operations that travel down the tree

Composite is not only about summing numbers. Any operation that makes sense for both single items and groups can follow the same recipe: a leaf handles it, a composite forwards it to each child and combines the results. Here, the operation is a search that returns paths, plus a count of leaves.

JS Searching and counting with recursion

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Each class owns the one decision that belongs to it. File says "I am a match or I am not"; Folder says "ask my children". No caller ever writes if (node instanceof Folder).

Transparency versus safety

There is one real design question: where do add() and remove() live?

  • Transparent composite. Declare add() and remove() on the component interface. Every node looks identical to clients, but a leaf must refuse the calls (usually by throwing), so you lose some compile-time safety.
  • Safe composite. Declare child management only on the composite. A leaf cannot be asked to add a child, but clients that want to build the tree must know which nodes are containers.

Neither is wrong. In statically typed languages such as Java or C++, the safe form is common because the compiler catches mistakes. In dynamic languages the transparent form is also popular, because code that only uses the tree (calls size()) is unaffected. The example below shows the transparent form with a leaf that refuses clearly.

JS A leaf that refuses children

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Practical details

  • Parent references. If nodes need to know their parent (to compute a full path or to remove themselves), store a parent field and set it inside add(). Keep the two links consistent in one place so they cannot drift apart.
  • Caching. A composite that recomputes size() on every call walks the whole subtree. If the tree is large and read often, cache the result and invalidate it up the parent chain when something changes.
  • Ordering. If children have an order (menu items, drawing layers), keep them in a list and decide whether add() can insert at a position.
  • Cycles. A node must never be added to its own descendants. A cycle turns recursion into an infinite loop; check for it in add() if untrusted code builds the tree.
  • Very deep trees. Recursion depth is limited by the call stack. For trees thousands of levels deep, switch to an iterative traversal with an explicit stack.

Where Composite appears in practice

  • The DOM. Every element, text node and the document itself are nodes; appendChild builds the tree and operations such as cloneNode(true) recurse through it.
  • GUI toolkits. A panel contains buttons, labels and other panels, and paint() is forwarded down the tree.
  • Vector drawing tools. A group of shapes behaves like one shape when you move or scale it.
  • Expression trees. A + node holds two operands, each of which may be a number or another operation. The Interpreter pattern builds on this.
  • Org charts and permissions. A team contains people and sub-teams; "total salary" or "all members" are recursive questions.

Composite combines well with Iterator (to walk the tree without exposing it), Visitor (to add operations without editing every node class) and Decorator, whose structure is similar but whose purpose is different: a decorator wraps exactly one component to add behavior, while a composite holds many to aggregate results.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main benefit of the Composite pattern?

    Composite gives leaves and containers a common interface, so callers do not need to check which kind of node they have.
  2. 2. In the file system example, how does Folder.size() produce its answer?

    A composite forwards the request to every child and combines the results. Because a child can be another folder, the request recurses through the whole subtree.
  3. 3. In the structure diagram, what do a Folder's children have to be?

    The composite holds references to the shared component type. That is what allows a folder to contain folders and makes arbitrary nesting possible.
  4. 4. What is the trade-off of putting add() and remove() on the component interface (the transparent form)?

    The transparent form makes every node look the same but forces leaves to implement child-management methods they cannot honor. The safe form avoids this at the cost of clients needing to know which nodes are containers.
  5. 5. How does Decorator differ from Composite, even though both are built from nested objects?

    The structures look alike, but the intent differs: a decorator enriches a single wrapped object, while a composite represents a part-whole tree of many objects.

Summary

  • Composite organizes objects into a tree where leaves and containers share one interface.
  • A leaf does the work itself; a composite forwards the request to its children and combines the answers, which gives recursion without type checks.
  • Declaring child management on the interface is transparent but unsafe for leaves; declaring it only on the composite is safe but less uniform.
  • Watch for cycles, very deep trees and repeated recomputation on large trees (cache and invalidate).
  • The DOM, GUI widget trees, drawing groups and expression trees are all composites.
  • Decorator wraps one object; Composite aggregates many.

Next lesson: Decorator.