composite
Compose objects into tree structures and treat individual objects and compositions uniformly.
SKILL.mdskills/code-quality/composite/SKILL.md
GitHubComposite
Allows clients to treat individual objects (leaves) and groups of objects (composites) identically via a shared interface. Perfect for tree-shaped structures.
When to Use
- You need to represent part-whole hierarchies (file system, UI component tree, org chart)
- Clients should be able to ignore the difference between single objects and groups
- Operations on a group should recursively apply to all children
How to Apply
- Define a
Componentinterface with operations common to both leaves and containers - Create
Leafclass implementingComponent(no children) - Create
Compositeclass implementingComponent; holds a list of childComponents - Composite delegates operations to its children and combines results
- Clients program to the
Componentinterface
Example
interface FileSystemEntry {
getSize(): number;
print(indent?: string): void;
}
class File implements FileSystemEntry {
constructor(private name: string, private size: number) {}
getSize() { return this.size; }
print(indent = '') { console.log(`${indent}📄 ${this.name} (${this.size}B)`); }
}
class Directory implements FileSystemEntry {
private children: FileSystemEntry[] = [];
constructor(private name: string) {}
add(e: FileSystemEntry) { this.children.push(e); }
getSize() { return this.children.reduce((s, c) => s + c.getSize(), 0); }
print(indent = '') {
console.log(`${indent}📁 ${this.name}`);
this.children.forEach(c => c.print(indent + ' '));
}
}