Skip to main content
Design Patterns 80 XP · 8 min

Composite: Tree Structures

Compose objects into tree structures and treat individual objects and groups uniformly — iterate a file system the same way whether it's a file or a folder.

Showing
Ad (728×90)

Why this matters

When you have a hierarchy of objects — menus containing sub-menus, folders containing files, UI components containing other components — client code tends to ask "is this a leaf or a container?" before acting. That type-checking spreads everywhere and breaks when you add new node types. Composite gives leaves and containers the same interface. Client code calls size() on a file or a folder — it doesn't know and doesn't care which one it is.

The problem

Bad

The solution

Good

Where Composite appears in the wild

The DOM is a Composite — element.textContent works on a single element or an entire subtree. React's component tree is a Composite — rendering a leaf component and a compound component uses the same render() call. Organization charts, bill-of-materials lists, and expression trees (where a sub-expression is itself an expression) all follow the same pattern.

Key takeaway

When clients should treat individual items and groups identically, Composite gives both the same interface — the tree collapses to a single method call.

Done with this lesson?

Mark it complete to earn XP and track your progress.