Composite: Trees & Hierarchies
You'll learn to
- -Model part-whole hierarchies (file systems, org charts, UI trees) so clients treat individual objects and groups uniformly
- -Implement a Composite tree with a shared component interface for both leaf and container nodes
Composite lets you compose objects into tree structures to represent part-whole hierarchies, and - the part that actually matters for interviews - lets client code treat individual objects (leaves) and compositions of objects (containers) uniformly through one shared interface.
File System: The Canonical Example
A file system has Files (leaves, no children) and Directories (containers, which hold Files and other Directories). Both need to answer get_size() - a File returns its own size, a Directory returns the sum of its children's sizes. Composite defines a shared FileSystemComponent interface that both File and Directory implement, so any code computing total size never needs to know or check which kind of node it is looking at.
class FileSystemComponent(ABC):
@abstractmethod
def get_size(self) -> int: ...
class File(FileSystemComponent): # leaf - no children
def __init__(self, size: int):
self._size = size
def get_size(self) -> int:
return self._size
class Directory(FileSystemComponent): # container - holds other components
def __init__(self):
self._children: list[FileSystemComponent] = []
def add(self, component: FileSystemComponent) -> None:
self._children.append(component)
def get_size(self) -> int:
return sum(child.get_size() for child in self._children) # recursion
root = Directory()
root.add(File(100))
sub = Directory()
sub.add(File(50))
root.add(sub)
root.get_size() # 150 - works identically whether summing files or nested dirsThe Recursive Structure Is the Whole Point
Notice that Directory.get_size() calls get_size() on each child without checking whether that child is a File or another Directory - it just trusts the shared interface. This is what makes Composite genuinely recursive and arbitrarily deep for free: a Directory ten levels deep computes its size correctly with the exact same code as a Directory one level deep, because every level of the tree honors the same contract.
Composite pairs naturally with any "part of a whole" LLD prompt: org charts (Employee vs. Manager, both answering get_headcount()), UI component trees (a Panel containing Buttons and other Panels), and menu systems are all the same underlying shape.
Interview Signal is part of Pro
See a real weak answer next to a real strong one for this exact topic.
Quiz is part of Pro
Test what you just read with a short quiz, and bank the XP.