Composite
Build tree structures where single items and groups share one interface, so code can treat a whole group exactly like one item.
Description
Composite models part–whole hierarchies: folders and files, org charts, UI layouts, product bundles. Both leaves (a product) and composites (a bundle) implement the same interface, so a cart can ask any item for its price() without checking what it is.
A composite answers by asking its children and combining the results, here summing prices and applying a bundle discount. Because a bundle can contain other bundles, the structure nests to any depth and the calling code stays the same.
Class diagram
Composite pattern class diagram
- Class Cart with + total(): number.
- Interface CartItem with + price(): number, + describe(): string[].
- Class Product with + price(), + describe().
- Class Bundle with + add(...items): this, + price(), + describe().
- Cart contains CartItem.
- Product implements CartItem.
- Bundle implements CartItem.
- Bundle children 0..* CartItem.
Sequence diagram
Composite pattern sequence diagram
- Cart → Office starter: price().
- Office starter → Coffee kit: price().
- Coffee kit → Grinder: price().
- Coffee kit receives "60" back from Grinder.
- Coffee kit → Coffee kit: (60 + 20) × 0.9.
- Office starter receives "72" back from Coffee kit.
- Office starter → Mug: price().
- Office starter receives "10" back from Mug.
- Cart receives "77.90" back from Office starter.
TypeScript example
Products and bundles in a shopping cart. A bundle can hold products and other bundles, applies its own discount, and the cart prices everything with one call. (The diagram skips the beans to stay small.)
// Composite: a cart item can be a single product or a bundle of items,
// and the cart treats both the same way.
// Component
interface CartItem {
readonly name: string;
price(): number;
describe(indent?: string): string[];
}
// Leaf
class Product implements CartItem {
readonly name: string;
private readonly unitPrice: number;
constructor(name: string, unitPrice: number) {
this.name = name;
this.unitPrice = unitPrice;
}
price(): number {
return this.unitPrice;
}
describe(indent = ""): string[] {
return [`${indent}${this.name}: ${this.unitPrice.toFixed(2)}`];
}
}
// Composite: holds children (products or other bundles) and adds rules on top
class Bundle implements CartItem {
readonly name: string;
private readonly children: CartItem[] = [];
private readonly discount: number;
constructor(name: string, discount = 0) {
this.name = name;
this.discount = discount;
}
add(...items: CartItem[]): this {
this.children.push(...items);
return this;
}
price(): number {
const sum = this.children.reduce((total, child) => total + child.price(), 0);
return Math.round(sum * (1 - this.discount) * 100) / 100;
}
describe(indent = ""): string[] {
const head = `${indent}${this.name} (−${this.discount * 100}%): ${this.price().toFixed(2)}`;
return [head, ...this.children.flatMap((c) => c.describe(indent + " "))];
}
}
export function demo(): string[] {
const coffeeKit = new Bundle("Coffee kit", 0.1).add(new Product("Grinder", 60), new Product("Beans 1 kg", 20));
const starter = new Bundle("Office starter", 0.05).add(coffeeKit, new Product("Mug", 10));
const cart: CartItem[] = [starter, new Product("Notebook", 5)];
const total = cart.reduce((sum, item) => sum + item.price(), 0);
return [...cart.flatMap((item) => item.describe()), `total: ${total.toFixed(2)}`];
}When to use it
Use it when
- Your data is naturally a tree, and you want to run the same operation over a single node or a whole branch.
- Clients shouldn't care whether they hold one item or a group: menus and submenus, files and folders, shapes and groups of shapes.
- Groups add their own rules on top of their children, such as a bundle discount or a folder's total size.
Avoid it when
- The structure is a flat list. An array and a loop are enough.
- Leaves and groups need very different operations. A shared interface full of methods that don't apply to one side is a smell.
- The tree is very deep or very large and performance-sensitive. Recursive calls on every query may be too slow without caching.
Pitfalls
- Putting
add()andremove()on the shared interface, so leaves must implement methods that make no sense for them. Keep child management on the composite. - Cycles: adding a bundle to itself, directly or through another bundle, causes infinite recursion. Guard against it if users build the tree.
- Recomputing totals over large trees on every call. Cache, and invalidate when children change.
Alternatives
Decorator
Choose it when each wrapper has exactly one child and adds behaviour, rather than grouping many children.
Visitor
Choose it when you need many different operations over the same tree without adding a method to every node class.
Iterator
Choose it when callers mainly need to walk the tree in some order, not compute over it.