Composite Pattern

Build tree structures where a single item and a group of items share one interface, so callers run the same operation on either without checking which they hold.

Overview

The problem it solves Some data is a tree: folders hold files and folders, a UI panel holds buttons and panels, an expression holds numbers and sub-expressions. Code that walks such a tree tends to fill up with checks: is this a leaf or a group? The Composite pattern gives leaves and groups one interface. A group implements each operation by asking its children, and the recursion takes care of the rest.

The pattern is a structural pattern from the Gang of Four book (Gamma, Helm, Johnson and Vlissides, *Design Patterns*, 1994). Its roles are Component (the shared interface), Leaf (an item with no children) and Composite (a node that holds children of type Component).

In the file system example below, the three roles have concrete names. Node is the Component, an interface with name() and size(). File is a Leaf: it keeps its own bytes and answers both methods itself. Directory is the Composite: it keeps children, a list of Node, answers the same two methods, and adds add(child). Both File and Directory implement Node, and because the children are typed as Node, a child can be a leaf or another composite.

Interview questions

  • What are the roles in the Composite pattern, and what does each one own?
  • Show the smell that Composite removes, and the fix.
  • Where should add and remove go: on the Component or only on the Composite?
  • How do you stop a composite from containing itself, and do children need a parent link?
  • How do Iterator and Visitor fit with a composite?

Sign up free to read the full topic

More Low-Level Design topics

Start free on Cariara · Coding problems · System design studio