Composite

Treating individual objects and groups uniformly with tree structures — file systems, UI trees, expression trees, recursive operations, and transparency vs safety trade-offs.

Intermediate 2 min readLesson 12 of 24

Intent: compose objects into tree structures to represent part-whole hierarchies, and let clients treat individual objects and compositions uniformly.

Whenever you have "a thing that can contain things of the same kind" — folders and files, UI containers and widgets, an organisation chart, a nested menu, an expression (2 + 3) * 4 — Composite lets you call one operation on the root and have it recurse naturally.

app.ts 4KButil.ts 2KBsrc (dir)README 1KBlogo.png 30KBassets (dir)/ (dir)

Asking the root for its size returns 37 KB: each directory sums its children, each file returns its own size.

Structure

  • Component: the common interface (size(), render(), evaluate()).
  • Leaf: an individual object with no children.
  • Composite: holds children (Components) and implements operations by delegating to them.
interface Node {
    String name();
    long size();
    default void print(String indent) { System.out.println(indent + name() + " (" + size() + ")"); }
}

record File(String name, long size) implements Node {}

final class Directory implements Node {
    private final String name;
    private final List<Node> children = new ArrayList<>();
    Directory(String name) { this.name = name; }

    Directory add(Node n) { children.add(n); return this; }
    public String name() { return name; }

    public long size() {                                   // recursion over the tree
        return children.stream().mapToLong(Node::size).sum();
    }
    @Override public void print(String indent) {
        Node.super.print(indent);
        children.forEach(c -> c.print(indent + "  "));
    }
}

Directory root = new Directory("/")
    .add(new Directory("src").add(new File("app.ts", 4096)).add(new File("util.ts", 2048)))
    .add(new File("README", 1024));
System.out.println(root.size());     // 7168: client doesn't care what is a file vs a dir

Expression trees

Composite is how interpreters and calculators represent expressions — literals are leaves, operators are composites (Parsing):

TypeScript
type Expr =
  | { kind: "num"; value: number }
  | { kind: "add" | "mul"; left: Expr; right: Expr };

const evaluate = (e: Expr): number =>
  e.kind === "num" ? e.value
  : e.kind === "add" ? evaluate(e.left) + evaluate(e.right)
  : evaluate(e.left) * evaluate(e.right);

// (2 + 3) * 4
evaluate({ kind: "mul", left: { kind: "add", left: { kind: "num", value: 2 }, right: { kind: "num", value: 3 } }, right: { kind: "num", value: 4 } });  // 20

Transparency vs safety

Where do child-management methods (add, remove) live?

Designadd() declared onProsCons
TransparentComponent (all nodes)Clients treat everything identicallyCalling add on a leaf must throw
SafeComposite onlyType system prevents misuseClients sometimes need to check the type

Most modern code prefers safe.

In the wild

  • UI frameworks: the DOM, React component trees, Swing/JavaFX containers — render() and layout recurse.
  • File systems and ASTs in compilers.
  • Graphics: scene graphs where a group transforms all its children.
  • Org charts, menus, bills of materials, permission groups (a group contains users and other groups).

Composite pairs naturally with Iterator (walk the tree) and Visitor (add operations over the tree without changing node classes — see Mediator, Memento & Visitor).

Key takeaways
  • Composite models part-whole trees where leaves and groups share one interface.
  • Operations on a composite recurse over its children.
  • Used for file systems, UI trees, ASTs and scene graphs.
  • Prefer the "safe" design: child management only on composites.