Composite
Treating individual objects and groups uniformly with tree structures — file systems, UI trees, expression trees, recursive operations, and transparency vs safety trade-offs.
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.
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 dirfrom dataclasses import dataclass, field
@dataclass
class File:
name: str
size_bytes: int
def size(self) -> int: return self.size_bytes
def print(self, indent=""): print(f"{indent}{self.name} ({self.size()})")
@dataclass
class Directory:
name: str
children: list = field(default_factory=list)
def add(self, node):
self.children.append(node)
return self
def size(self) -> int:
return sum(c.size() for c in self.children)
def print(self, indent=""):
print(f"{indent}{self.name}/ ({self.size()})")
for c in self.children:
c.print(indent + " ")
root = Directory("/").add(Directory("src").add(File("app.ts", 4096))).add(File("README", 1024))
print(root.size())interface FsNode { name: string; size(): number; }
class FileNode implements FsNode {
constructor(public name: string, private bytes: number) {}
size() { return this.bytes; }
}
class DirNode implements FsNode {
private children: FsNode[] = [];
constructor(public name: string) {}
add(n: FsNode) { this.children.push(n); return this; }
size(): number { return this.children.reduce((s, c) => s + c.size(), 0); }
}
const root = new DirNode("/")
.add(new DirNode("src").add(new FileNode("app.ts", 4096)))
.add(new FileNode("README", 1024));Expression trees
Composite is how interpreters and calculators represent expressions — literals are leaves, operators are composites (Parsing):
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 } }); // 20Transparency vs safety
Where do child-management methods (add, remove) live?
| Design | add() declared on | Pros | Cons |
|---|---|---|---|
| Transparent | Component (all nodes) | Clients treat everything identically | Calling add on a leaf must throw |
| Safe | Composite only | Type system prevents misuse | Clients 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).
- 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.