Composite Pattern
Treat an individual item and a group of items through the same component contract.
· Last updated: 2026-11-07 · 11 min read
Overview
A file's size can be read directly, but a folder's size is the sum of its files and subfolders. If callers check every item to decide whether it is a file or a folder, the same branch is repeated throughout the code that handles the tree, including when it encounters subfolders.
Composite gives individual items and groups, such as files and folders, the same interface. A caller can ask either for its size, and the folder object answers by adding up its children's sizes. An item with no children is a Leaf; a group that holds children is a composite.
UML
The UML shows Entry as the contract shared by the leaf and the group. FileEntry and Folder derive from Entry. Because Folder refers to Entry objects in turn, a folder can contain folders, and Bytes is the total of all its children's values.
History
GoF cataloged Composite as a structural pattern in Design Patterns in 1994. It represents part-whole hierarchies through a shared interface.1
Treating primitive shapes and nested groups uniformly under a single component interface took root in Xerox PARC's Smalltalk-80 view hierarchy (where every View could contain subviews) and in InterViews' Interactor / Scene composition model.2 File-system directories, GUI widget trees, and document outlines all share this exact part–whole structure.
Why use it?
Here Entry.Bytes is the only channel for asking about size. What a caller reads is a single Entry.Bytes, and walking a folder nested several levels deep is left to the recursive calls inside Folder.
Letting leaves add children makes a leaf look like a group. The example does not force a child-adding method on every component: its leaves only read, and the children are handed to Folder when it is constructed.
Designing a Composite always faces a trade-off between transparency and type safety over where child-management methods such as Add and Remove live. Putting them on the base Entry gives leaves and composites an identical interface at the cost of leaves having to ignore or reject child additions at runtime; keeping child storage on Folder alone lets the compiler reject attempts to add children to a FileEntry.
Example
This example puts two files into a folder and reads the combined size. It works entirely in memory rather than touching a real file system, and the caller reads the size without branching on whether an item is a file or a folder.
using System;
using System.Collections.Generic;
using System.Linq;
Entry folder = new Folder(new FileEntry(10), new FileEntry(20));
Console.WriteLine(folder.Bytes);
// Give callers the same read contract for leaves and groups.
abstract record Entry
{
public abstract long Bytes { get; }
}
sealed record FileEntry(long Length) : Entry
{
public override long Bytes => Length;
}
// Read the shared property recursively instead of checking each child’s concrete type.
sealed record Folder : Entry
{
private readonly Entry[] children;
public Folder(params Entry[] children) => this.children = children.ToArray();
public override long Bytes => children.Sum(entry => entry.Bytes);
}
30Folder reads its children through Bytes without checking their concrete types. The summing side has no type test.
An extended example
Once a folder sits inside another folder, a single file and a group read side by side from the same Entry list. Depth grows; the caller's code does not.
In the first example, every child of the folder was a file, so one sum was enough. Now one child is another folder. The outer folder needs that inner folder's result before it can finish its own sum, so reading Bytes sends the calculation down the tree and brings the totals back up.
The first entry is a file and returns its own size, 7, directly. For the second entry, the outer folder reads 5 from its first child, then asks the inner folder for its size. The inner folder returns 10+20=30, which the outer folder adds to the 5 already read, returning 35.
using System;
using System.Collections.Generic;
using System.Linq;
Entry[] entries =
{
new FileEntry(7),
new Folder(new FileEntry(5), new Folder(new FileEntry(10), new FileEntry(20)))
};
foreach (Entry entry in entries) Console.WriteLine(entry.Bytes);
// Give callers the same read contract for leaves and groups.
abstract record Entry
{
public abstract long Bytes { get; }
}
sealed record FileEntry(long Length) : Entry
{
public override long Bytes => Length;
}
// Read the shared property recursively instead of checking each child’s concrete type.
sealed record Folder : Entry
{
private readonly Entry[] children;
public Folder(params Entry[] children) => this.children = children.ToArray();
public override long Bytes => children.Sum(entry => entry.Bytes);
}
7
35In this example, Folder copies its child array at construction and offers no add operation afterward. Because Folder is a record, the compiler-generated equality compares the child array by reference, so two folders with identical contents are not equal unless they share that array. Extending this into a tree whose structure changes means preventing cycles, deciding what the total covers, and settling when it is refreshed.
TypeScript example
Porting the example to TypeScript keeps the same split. Entry lets callers read files and folders without distinguishing their concrete types. A file returns its own size; a folder sums its children, keeping recursive aggregation inside Folder.
// Give callers the same read contract for leaves and groups.
abstract class Entry { abstract get bytes(): bigint; }
class FileEntry extends Entry {
constructor(private readonly length: bigint) { super(); }
override get bytes(): bigint { return this.length; }
}
// Read the shared property recursively instead of checking each child’s concrete type.
class Folder extends Entry {
private readonly children: readonly Entry[];
constructor(children: readonly Entry[]) { super(); this.children = [...children]; }
override get bytes(): bigint {
return this.children.reduce((total, child) => total + child.bytes, 0n);
}
}
const entries: Entry[] = [
new FileEntry(7n),
new Folder([new FileEntry(5n), new Folder([new FileEntry(10n), new FileEntry(20n)])]),
];
for (const entry of entries) console.log(entry.bytes.toString());7
35Because a file size is an integer, the TypeScript examples use bigint and convert it to a string for output. The constructor copies the child array, and nothing here touches a real file system.
Folding leaves and groups with Composite<T>
Any operation that combines child results of type T into a single T (sums, maximums, boolean conjunctions, or label lists) fits a generic Composite<T>. Leaf<T> returns its stored value directly, while Composite<T> folds its children's Evaluate() results using an initial seed and a combine function.
The example below uses the same Composite<int> first with addition to compute a nested total (35) and then with Math.Max to find the largest leaf (20).
C#
using System;
using System.Collections.Generic;
using System.Linq;
IComponent<int>[] nodes =
{
new Leaf<int>(7),
new Composite<int>(0, (total, next) => total + next,
new Leaf<int>(5),
new Composite<int>(0, (total, next) => total + next, new Leaf<int>(10), new Leaf<int>(20)))
};
foreach (IComponent<int> node in nodes) Console.WriteLine(node.Evaluate());
IComponent<int> maxTree = new Composite<int>(
0,
Math.Max,
new Leaf<int>(7),
new Composite<int>(0, Math.Max, new Leaf<int>(20), new Leaf<int>(12)));
Console.WriteLine(maxTree.Evaluate());
interface IComponent<T> { T Evaluate(); }
sealed record Leaf<T>(T Value) : IComponent<T>
{
public T Evaluate() => Value;
}
sealed class Composite<T> : IComponent<T>
{
private readonly T seed;
private readonly Func<T, T, T> combine;
private readonly IComponent<T>[] children;
public Composite(T seed, Func<T, T, T> combine, params IComponent<T>[] children)
{
this.seed = seed;
this.combine = combine;
this.children = children.ToArray();
}
// Fold leaf and child-composite results with the same combining rule.
public T Evaluate() => children.Aggregate(seed, (acc, child) => combine(acc, child.Evaluate()));
}7
35
20TypeScript
interface Component<T> { evaluate(): T; }
class Leaf<T> implements Component<T> {
readonly #value: T;
constructor(value: T) { this.#value = value; }
evaluate(): T { return this.#value; }
}
class Composite<T> implements Component<T> {
readonly #seed: T;
readonly #combine: (acc: T, next: T) => T;
readonly #children: readonly Component<T>[];
constructor(seed: T, combine: (acc: T, next: T) => T, children: readonly Component<T>[]) {
this.#seed = seed;
this.#combine = combine;
this.#children = [...children];
}
// Fold leaf and child-composite results with the same combining rule.
evaluate(): T {
return this.#children.reduce((acc, child) => this.#combine(acc, child.evaluate()), this.#seed);
}
}
const nodes: Component<number>[] = [
new Leaf(7),
new Composite(0, (a, b) => a + b, [
new Leaf(5),
new Composite(0, (a, b) => a + b, [new Leaf(10), new Leaf(20)]),
]),
];
for (const node of nodes) console.log(node.evaluate());
const maxTree = new Composite(0, Math.max, [
new Leaf(7),
new Composite(0, Math.max, [new Leaf(20), new Leaf(12)]),
]);
console.log(maxTree.evaluate());7
35
20This generic form works cleanly when leaves and composites return the same type T under one combining rule. When distinct node kinds need open-ended operations with different return types, a Visitor or discriminated union is usually a better fit.
When it becomes an anti-pattern
Forcing unrelated node types into a single component interface backfires when most operations make sense only for leaves or only for groups: leaf classes fill up with no-op methods or NotSupportedException throws, and callers end up downcasting anyway. Mutable trees add a structural hazard: if a node is attached under two parents or an ancestor is linked as its own descendant, recursive calls like Bytes or Evaluate() silently double-count shared subtrees or overflow the call stack.
When the set of node kinds is fixed and closed—such as files and folders, or JSON values—modeling the hierarchy as an algebraic sum type (discriminated union) and reducing it with a recursive Fold is often simpler than an open class hierarchy and gives you compile-time exhaustiveness checking for free. And if a mutable Composite caches upward parent pointers or precomputed aggregates (such as cached directory byte counts), every child insertion, removal, or move must maintain bidirectional link invariants and propagate cache invalidation all the way to the root.
Related reading
Footnotes
- Gamma, Helm, Johnson, Vlissides. Design Patterns (1994). Publisher record. Structural patterns, Composite. ↩
- Glenn E. Krasner and Stephen T. Pope, "A Cookbook for Using the Model-View-Controller User Interface Paradigm in Smalltalk-80," Journal of Object-Oriented Programming 1(3), 1988, pp. 26–49. ↩