Intermediate LevelSoftware Engineering Principles
What is the Composite Pattern and how does it represent tree-structured hierarchies?
❓ Interview Prompt: Explain the Composite Structural Pattern, Part-Whole hierarchies, Leaf vs Composite nodes, and uniform tree node treatment.
The Composite Pattern composes objects into tree structures to represent Part-Whole hierarchies, allowing clients to treat individual objects (Leaf) and compositions of objects (Composite) uniformly:
Use Case:
File system structures (Files vs Directories containing Files/Directories) or UI Component trees.
Code Implementation Example
typescript
interface FileSystemItem { getSize(): number; }
class FileItem implements FileSystemItem {
constructor(private size: number) {}
getSize() { return this.size; }
}
class DirectoryItem implements FileSystemItem {
private items: FileSystemItem[] = [];
add(item: FileSystemItem) { this.items.push(item); }
getSize() { return this.items.reduce((acc, i) => acc + i.getSize(), 0); }
}💡Calculating total file sizes recursively using the Composite pattern.
🎯 Interview Key Takeaway
Use the Composite pattern to treat individual leaf items and container nodes uniformly in tree structures.
#Composite#Design Patterns#Structural#Intermediate
Back to all Software Engineering Principles Questions→