Composite is for data shaped like a tree: folders that hold files and other folders, menus that hold items and submenus, a UI made of panels that hold buttons and other panels. It gives single objects (leaves) and groups (composites) one shared interface, so client code can call size() or render() on any node without asking what kind it is. A composite answers by calling the same method on each of its children and combining the results, so one call on the root walks the whole tree.
Think of it like
A company's headcount
Ask a CEO how many people work in the company. She does not walk the building counting desks; she asks each of her direct reports for the size of their part. A department head asks the team leads, a team lead counts the team, and an individual contributor simply answers "one". Everyone answers the same question in the same form, so the CEO never needs to know whether a direct report runs a department of 300 or is a single assistant. The question fans out down the org chart, and the numbers add up on the way back.
The problem
A storage app needs the size of a folder. A folder holds files and other folders, nested to any depth. The first design gives the two kinds of item nothing in common: a File is plain data, and a Folder holds a list of File | Folder and works out its size by checking each item's type. This is the Before version in the visualizer above.
type Item = File | Folder;
class File {
constructor(readonly name: string, readonly bytes: number) {}
}
class Folder {
private items: Item[];
constructor(readonly name: string, ...items: Item[]) {
this.items = items;
}
add(item: Item) {
this.items.push(item);
}
size(): number {
let total = 0;
for (const it of this.items) {
if (it instanceof File) total += it.bytes;
else total += it.size(); // must be a Folder
}
return total;
}
}It returns the right number. The trouble is where the knowledge lives: the code that walks the tree must know every kind of item and how to handle each one.
- Type checks spread.
size()branches oninstanceof. So will every other walk over the tree: counting files, searching by name, printing a listing, copying, deleting. Each one repeats the same branch. - A new kind of item edits old code. Supporting symbolic links means widening the
Itemunion and adding a branch to every walk. Forget one, and that walk treats a link as a folder and crashes or miscounts. - Leaves are passive.
Folderreadsit.bytesfrom the outside. The file cannot decide how its own size is computed (compressed, sparse, a link), because nobody asks it. - Clients face the same choice. Any code holding "some item" has to check what it is before it can ask a question, which is the opposite of polymorphism.
The pattern
Intent: compose objects into tree structures to represent part-whole hierarchies, and let clients treat individual objects and compositions of objects uniformly (Gang of Four). In practice: one interface for every node, leaves that answer directly, and composites that answer by asking their children.
- Component (
Node) - The interface every node implements, here
size(). Clients and composites hold references of this type only. - Leaf (
File,Link) - A node with no children. It does the real work of an operation: a file returns its bytes, a link the length of its target path.
- Composite (
Folder) - A node that holds children typed as the component (
children: Node[]) and offers ways to manage them (add()). It implements each operation by calling it on every child and combining the answers. - Client
- Builds the tree and calls operations on any node through the component interface:
root.size()anddocs.size()look the same to it.
Two arrows in the class diagram carry the whole idea. Folder implements Node, so a folder can stand anywhere a node can. And Folder contains Nodes, so its children can be files, links or more folders. That loop (a composite is a component and holds components) is what makes the structure recursive to any depth without any class knowing the depth. And the recursion needs no if: when Folder.size() calls c.size() on a file, File.size runs and the recursion stops there, so the leaves are the base case, chosen by dynamic dispatch.
What the visualizer shows
- Class diagram:
Nodeon top,FileandFolderimplementing it, and a composition fromFolderback up toNodelabeled*(any number of children). Eachsize()call lights the class whose code runs and the violetNodeinterface that declares it; a call from a folder to a child also lights that composition. - Objects at runtime: the tree itself, parent above children:
rootholdsdocs,todoandshare;docsholdscvandtax. Eachchildrenlist is drawn as arrows to the child objects. Duringroot.size()the message travels down the arrows to every node, and each return carries a number back up. - Sequence of calls: one
size()from the client becomes nested activation bars:rootcallsdocs,docscallscvandtax, thenrootcallstodoandshare. The returns read900,400,1300,60,0and finally1360: the sums building up level by level.
Press Play, or step with the arrow buttons; the visualizer runs the classes in the code panel for real, and the caption under the stage explains each step. The Before / With Composite toggle switches to the type-checking version, where only folders ever receive a message and each file is read from the outside. Add links applies the change request to whichever version is shown; touched classes get a badge, and the Change request panel beside the code compares the two versions.
Walkthrough
- 1
Build the leaves first
With With Composite selected, the client creates
cv(900 bytes) andtax(400). They are leaves: a name, a size, and asize()that returns it. - 2
A composite holds nodes
new Folder("docs", cv, tax)createsdocswithchildren = [cv, tax]. The list is typedNode[], so the folder never stores what kind each child is. - 3
Mix kinds in one list
The client creates the file
todo(60) and thenrootwithchildren = [docs, todo]: a folder and a file side by side. An empty foldersharefollows. - 4
add() takes any node
root.add(share)pushes the folder ontoroot.children, which becomes[docs, todo, share]. A file or a link would be added the same way. - 5
One call on the root
The client calls
root.size().Folder.sizeruns and loops over the children, callingsize()on each through theNodeinterface. - 6
The call fans out
rootasksdocs, which runsFolder.sizeone level down and askscv(900) andtax(400).docsreturns1300toroot. Three activation bars are stacked at that moment:root,docsand a leaf. - 7
The results sum back up
rootthen askstodo(60) andshare, whose loop has nothing to visit and returns0.rootreturns1360to the client, which wrote no loop and no type check. - 8
Add links (change request)
With Add links applied,
shareis built withnew Link("cv", "docs/cv"). Duringroot.size()the call goes one level deeper,shareaskslink,Link.sizereturns7(the length ofdocs/cv), and the total becomes1367.Folderdid not change.
Before and after
Folder checks types
FileandFoldershare no interface; items are a union type- Every walk over the tree branches on
instanceof - Files are read from the outside; only folders get messages
- A new kind of item edits the union and every walk
- Clients holding "some item" must check its type first
With Composite
- One
Nodeinterface for leaves and composites - Each class answers for itself; folders only delegate and combine
- Every node receives the call; dispatch replaces the type check
- A new kind of node is one new class
- Any subtree answers the same question:
docs.size()works too
| Change request: add symbolic links | Before | With Composite |
|---|---|---|
| Existing classes edited | 1 (Folder) | 0 |
| New classes | 1 (Link) | 1 (Link) |
| Lines changed in existing classes | 2 | 0 |
The panel counts classes, so it leaves out one more edit in the Before version: the Item union becomes File | Folder | Link. And the Before code has only one operation that walks the tree. A real file model has several (count, find, print, copy, delete), and each one would need the same new instanceof Link branch; with Composite each of those is one more method on Link and nothing else.
Variations
Transparency or safety: where add() lives
The visualizer puts add() only on Folder. That is the safe design: calling add() on a file is a compile error, but a client holding a Node must find out it is a folder before adding to it. The Gang of Four describe the alternative, the transparent design, and lean toward it: declare add(), remove() and getChild() on the component itself, so every node looks the same, and make leaves fail (or do nothing) at runtime.
| Aspect | Safe (add() on the composite only) | Transparent (add() on the component) |
|---|---|---|
Calling add() on a leaf | Does not compile | Compiles; throws or is ignored at runtime |
| Client code that builds trees | Needs the concrete Folder type, or a check | Works with any Node |
| Component interface | Small: only the real operations | Larger: child management on every node |
| Real example | Most typed application code | The DOM: appendChild is declared on Node, and calling it on a text node throws a HierarchyRequestError |
A common middle ground keeps the interface safe and adds a query: asFolder(): Folder | null, or in TypeScript a type guard, so clients that must add children can ask without a cast. Choose based on who builds the tree. If construction happens in one place (a parser, a builder, a config loader), the safe design costs little; if arbitrary client code edits trees through generic references, transparency is more convenient.
Parent references and cached totals
Children often need to know their parent: to compute a path (root/docs/cv), to bubble an event up, or to remove themselves. Store parent on the component and set it in exactly one place, the composite's add() and remove(), so the two directions of the link can never disagree. The DOM's parentNode and AWT's Component.getParent() work this way. A node with a single parent field can be in only one place in the tree; moving it means removing it from the old parent first.
root.size() visits every node, which is fine for a small tree and slow for a disk with a million files that is asked often. A composite can cache its total and clear the cache when anything below it changes. Clearing has to travel up: a file that grows must invalidate its folder, that folder's parent, and so on to the root, which is another reason for parent references. The second implementation below does exactly this.
Ordering, depth and cycles
- Ordering. When child order matters (paragraphs in a document, draw order in a scene, menu items), keep a list and offer positional operations such as
insertBefore(). When it does not, a set or map can make lookup and removal cheaper. - Depth. Each level is one stack frame. Ordinary trees are shallow, but a machine-generated tree (a deeply nested JSON document, a long chain of nested expressions) can overflow the stack; walk such trees with an explicit stack or queue instead, which is what an Iterator over the tree can encapsulate.
- Cycles. A composite must never contain itself, directly or through a descendant, or every recursive operation loops forever. Check in
add(): walk up from the new parent and refuse if you meet the node being added. The DOM throws aHierarchyRequestErrorwhen you try to insert a node into its own descendant. - Shared children. If the same object may appear under two parents, the structure is a directed acyclic graph, not a tree: a single
parentfield no longer works and totals may count a node twice. Sharing leaves to save memory is Flyweight's job, and the shared leaves then must not store their position.
Operations from outside: visitors and iterators
Each new operation added to the component interface touches every class in the hierarchy. When the node types are stable but operations keep coming (size, print, export to JSON, find duplicates), a Visitor lets you write each operation as one class that the tree accepts. When clients just need to go through the nodes (all files under docs, depth first), an Iterator keeps the traversal order out of client code. Building a large tree is often a job for a Builder, which can enforce rules such as "no cycles" or "no empty groups" while assembling it.
In real code
| Where | Component | Leaves and composites |
|---|---|---|
| The browser DOM | Node | Text and Comment nodes are leaves; Element, Document and DocumentFragment hold childNodes. textContent on an element returns the text of all its descendants |
| Java AWT and Swing | java.awt.Component | java.awt.Container extends Component and holds components through add(). Swing's JComponent extends Container, so even a JButton is technically a container (the transparent design) |
| File systems | A directory entry | Files and symbolic links are leaves; directories hold entries. du reports a directory's disk usage by summing what it contains |
| Scene graphs (Three.js, game engines) | Object3D in Three.js | Meshes, lights and groups are all Object3Ds with children, add(), parent and traverse(); a parent's transform applies to its whole subtree |
| Compilers and interpreters | An AST node | Literals and identifiers are leaves; expressions and statements hold child nodes. Evaluating or type-checking an expression evaluates its children |
| UI frameworks (React and others) | A component or element | A component renders other components and host elements, which nest to any depth; rendering the root renders the whole tree |
The UI frameworks show the pattern from the client's side: you write <Sidebar> without knowing whether it renders one link or a nested menu of fifty, and you can move it anywhere a component fits. AWT shows the trade-off from the library's side: making Container a Component lets a panel go anywhere a button can, and its layout managers size a container by asking its children for their preferred sizes, which is the same fan-out as size() in the visualizer.
When to use it, and when not to
Reach for Composite when
- The data is a part-whole hierarchy of any depth: files, menus, UI, shapes, org charts, expressions
- Clients should not care whether they hold one object or a group
- Operations on a group are naturally defined by its members (sum, render all, enable all)
- New kinds of leaf or group keep appearing
Skip it when
- The structure is flat or has a fixed depth (an order with lines is just a list)
- Leaves and groups support very different operations, so a shared interface would be mostly stubs
- Nodes are shared between parents (a graph): you need graph algorithms with visited sets, not plain recursion
- The node types are fixed and only operations grow: consider Visitor, or a union type with exhaustive matching
Composite vs similar patterns
| Pattern | Structure | Purpose | Key difference |
|---|---|---|---|
| Composite | A tree: a node holds many children of the component type | Treat one and many uniformly; operations recurse and combine | Many children, and the result is usually an aggregate of theirs |
| Decorator | A chain: each wrapper holds exactly one component | Add behavior to an object without changing its interface | One wrapped child, and the wrapper adds to its answer instead of combining many. A decorator is sometimes called a degenerate composite |
| Iterator | Any collection, including a composite tree | Visit elements one at a time without exposing the structure | About traversal order, not about structure. Often used to walk a composite |
| Visitor | A fixed set of node classes, often a composite | Add new operations without editing the node classes | Complements Composite: the tree provides the structure, visitors provide the operations |
| Interpreter | An abstract syntax tree | Evaluate sentences in a small language | A specialized composite: grammar rules are composite classes, terminals are leaves, and interpret() recurses |
| Flyweight | Many fine-grained objects sharing intrinsic state | Save memory with many similar objects | Often used inside a composite to share leaves; shared leaves cannot hold parent references |
Implementation
The visualizer's scenario as a complete program: a Node component with File and Link leaves and a Folder composite. A second operation, print, shows that every new walk over the tree is one method per class and no type checks. The demo builds the tree from the visualizer, including the link from the change request, and asks the root and a subtree for their sizes.
from abc import ABC, abstractmethod
class Node(ABC):
"""Component: every node in the tree answers these."""
def __init__(self, name: str) -> None:
self.name = name
@abstractmethod
def size(self) -> int: ...
@abstractmethod
def print(self, indent: str = "") -> None: ...
class File(Node):
"""Leaf: a file has no children."""
def __init__(self, name: str, size_bytes: int) -> None:
super().__init__(name)
self._bytes = size_bytes
def size(self) -> int:
return self._bytes
def print(self, indent: str = "") -> None:
print(f"{indent}{self.name} ({self.size()})")
class Link(Node):
"""Leaf from the change request: size is the length of its path."""
def __init__(self, name: str, target: str) -> None:
super().__init__(name)
self._target = target
def size(self) -> int:
return len(self._target)
def print(self, indent: str = "") -> None:
print(f"{indent}{self.name} -> {self._target} ({self.size()})")
class Folder(Node):
"""Composite: holds Nodes and answers by asking them."""
def __init__(self, name: str, *children: Node) -> None:
super().__init__(name)
self._children: list[Node] = list(children)
def add(self, node: Node) -> None:
self._children.append(node)
def remove(self, node: Node) -> None:
self._children.remove(node)
def size(self) -> int:
return sum(c.size() for c in self._children)
def print(self, indent: str = "") -> None:
print(f"{indent}{self.name}/ ({self.size()})")
for c in self._children:
c.print(indent + " ")
docs = Folder("docs", File("cv", 900), File("tax", 400))
root = Folder("root", docs, File("todo", 60))
share = Folder("share", Link("cv", "docs/cv"))
root.add(share)
print(root.size()) # 1367
print(docs.size()) # 1300: a subtree answers the same question
root.print()Key takeaways
- Composite gives leaves and groups one interface, so clients treat a single object and a whole tree the same way.
- A composite implements each operation by calling it on its children and combining the answers; the leaves are the base case, chosen by dynamic dispatch instead of
instanceof. - In the visualizer's "Add links" request, Composite adds 1 class and edits none; the type-checking version also edits
Folder(+2 lines) and theItemunion, and would edit every other walk over the tree. - Decide where
add()lives: on the composite only (safe, compile-time errors) or on the component (transparent, runtime errors, as in the DOM). - Production composites add parent references, cached aggregates invalidated upward, and a check that a node never contains itself.
- Use Visitor to add operations to a stable tree, Iterator to traverse it, and Builder to assemble it.
Common pitfalls
- Letting type checks creep back in: a client or composite that tests
child instanceof Folderhas lost the uniformity the pattern exists for. - Allowing cycles. Adding a folder to its own descendant makes every recursive operation loop until the stack overflows; check ancestry in
add(). - Updating only one side of a parent link. If
childrenandparentcan be changed separately they will disagree; change both only inadd()andremove(). - Caching totals without invalidating ancestors. A file that grows must clear the cache of every folder above it, not just its direct parent.
- Bloating the component interface with operations only composites support, so every leaf is full of methods that throw.
Interview tips
- When an LLD prompt has nesting (folders, menus, org charts, product bundles, permission groups, expression trees), name Composite early and sketch
Component,LeafandCompositewith the recursivecontainsarrow. - Raise the transparency vs safety trade-off on your own: say where
add()lives and why. It shows you know the pattern beyond the diagram. - Mention the production details: parent pointers, cached aggregates with upward invalidation, cycle checks, and recursion depth for very deep trees.
- Be ready to compare it with Decorator (one child vs many) and to pair it with Visitor for new operations.
Real-world applications
- File systems and storage browsers: sizes, counts, permissions and search over directory trees.
- UI toolkits and component frameworks: panels containing widgets and other panels, layout and rendering by recursion.
- Document models: the DOM, rich-text editors, and word processors' sections, paragraphs and runs.
- Graphics and games: scene graphs and grouped shapes that move, scale and draw as one.
- Compilers, query engines and rule engines: abstract syntax trees and expression trees.
- Business data: org charts, bills of materials, product bundles and nested menus or categories.
Test yourself
What does the Composite pattern let a client do?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.