Skip to main content

Sign in to CleanKata

Track your progress, earn XP, and unlock every lesson.

By signing in you agree to our Terms of Use and Privacy Policy.

Design Patterns80 XP8 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.

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.

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.

🔧 Some exercises may still have errors. If something seems wrong, use the Feedback button (bottom-right of the page) to report it — it helps us fix it fast.

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

✗ Your version

Composite: Tree Structures — CleanKata — CleanKata