पाठ 14 / 25
Composite
Treat leaves and trees the same way.
Part-whole hierarchies
Intent: compose objects into tree structures and let clients treat individual objects (leaves) and groups (composites) through one interface. File systems (files and folders), UI component trees, organisation charts, menus, and pricing bundles (a product or a bundle of products) are natural fits. Operations like "total size", "render" or "total price" are defined once on the shared interface; composites implement them by delegating to their children. Use it when your domain really is a tree and clients should not care about depth. Watch out for operations that only make sense on one kind of node (you cannot "add a child" to a file); keep those off the shared interface or handle them explicitly.
Products and bundles
A bundle prices itself by summing its children.
interface CatalogItem {
name: string;
priceCents(): number;
}
class Product implements CatalogItem {
constructor(public name: string, private cents: number) {}
priceCents() { return this.cents; }
}
class Bundle implements CatalogItem {
constructor(public name: string, private items: CatalogItem[], private discount = 0) {}
priceCents() {
const total = this.items.reduce((sum, item) => sum + item.priceCents(), 0);
return Math.round(total * (1 - this.discount));
}
}
const starterKit = new Bundle('Starter kit', [
new Product('Keyboard', 4_999),
new Product('Mouse', 2_499),
new Bundle('Cable pack', [new Product('USB-C cable', 999), new Product('HDMI cable', 1_299)]),
], 0.1);
starterKit.priceCents(); // the client does not care how deep the tree isNested boxes
Asking the weight of a box works the same whether it holds one book or more boxes of books: each box asks its contents and adds them up.
त्वरित जाँच: Which domain is a natural fit for Composite?
- Ensuring one database pool
- Retrying a failed HTTP request
- Choosing between payment providers
- A file system with files and folders
Answer
A file system with files and folders — Composite models part-whole trees.