Composite
Compose objects into tree structures and treat individual objects and groups uniformly.
Use it when
You model part-whole hierarchies such as menus, file systems or org charts.
/**
* Composite: treat a single file and a whole folder the same way.
*
* Real-world scenario: a file explorer showing sizes. A file has a size; a folder
* holds files and other folders, and its size is the total of everything inside.
* Both share one interface, so code that asks for size() or show() never needs to
* check whether it has a file or a folder.
*/
const kb = (size: number): string => `${size.toLocaleString("en-US")} KB`;
// Component: what files and folders have in common.
interface Item {
readonly name: string;
size(): number; // in KB
show(indent?: number): void;
}
// Leaf: has no children. (Named FileItem because File is a built-in browser type.)
class FileItem implements Item {
readonly name: string;
private readonly sizeKb: number;
constructor(name: string, sizeKb: number) {
this.name = name;
this.sizeKb = sizeKb;
}
size(): number {
return this.sizeKb;
}
show(indent = 0): void {
console.log(`${" ".repeat(indent)}${this.name} (${kb(this.size())})`);
}
}
// Composite: holds other items, files or folders, and delegates to them.
class Folder implements Item {
readonly name: string;
private readonly items: Item[];
constructor(name: string, items: Item[] = []) {
this.name = name;
this.items = items;
}
add(item: Item): void {
this.items.push(item);
}
size(): number {
return this.items.reduce((total, item) => total + item.size(), 0);
}
show(indent = 0): void {
console.log(`${" ".repeat(indent)}${this.name}/ (${kb(this.size())})`);
for (const item of this.items) {
item.show(indent + 2);
}
}
}
function clientCode(): void {
const photos = new Folder("photos", [
new FileItem("beach.jpg", 2_400),
new FileItem("party.jpg", 1_800),
]);
const documents = new Folder("documents", [new FileItem("resume.pdf", 120), photos]);
const home = new Folder("home", [documents]);
home.add(new FileItem("notes.txt", 4)); // folders can grow after creation
home.show();
// Same call for a single file or a whole tree.
for (const item of [new FileItem("todo.txt", 2), photos, home]) {
console.log(`${item.name}: ${kb(item.size())}`);
}
}
clientCode();
// Output:
// home/ (4,324 KB)
// documents/ (4,320 KB)
// resume.pdf (120 KB)
// photos/ (4,200 KB)
// beach.jpg (2,400 KB)
// party.jpg (1,800 KB)
// notes.txt (4 KB)
// todo.txt: 2 KB
// photos: 4,200 KB
// home: 4,324 KBHow it works
| Role | Classes | What it does |
|---|---|---|
| Component | Item | Shared interface: size() and show() |
| Leaf | FileItem | Has its own size and no children |
| Composite | Folder | Holds files and folders and passes calls down to them |
| Client | clientCode() | Calls size() the same way on a file or a whole tree |