QA
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→

More Software Engineering Principles Interview Questions

Beginner LevelSoftware Engineering Principles

Explain the 5 SOLID Principles of Object-Oriented Software Design with practical refactoring examples.

Beginner LevelSoftware Engineering Principles

What are DRY (Don't Repeat Yourself), KISS (Keep It Simple, Stupid), and YAGNI (You Aren't Gonna Need It)?

Beginner LevelSoftware Engineering Principles

Why is Composition Over Inheritance a fundamental object-oriented design principle?