What is the Composite Pattern?
Learn the Composite design pattern — tree structures, part-whole hierarchies and uniform interfaces — with a Java example.
Expected Interview Answer
The Composite pattern is a structural design pattern that composes objects into tree structures to represent part-whole hierarchies, letting clients treat individual objects and compositions of objects through the same uniform interface.
Both leaf nodes (individual objects) and composite nodes (containers of other components, which may themselves be leaves or composites) implement a common component interface. A client calling an operation on a composite simply delegates that call recursively to each child, without needing to know whether it is dealing with a single object or an entire subtree. This eliminates type-checking branches like 'if it’s a leaf do X, if it’s a composite do Y' throughout client code, and makes adding new component types straightforward as long as they honor the shared interface.
- Uniform treatment of individual objects and groups of objects
- Simplifies client code by removing type-checking branches
- Naturally models recursive, tree-shaped structures
- New component types can be added without changing client code
AI Mentor Explanation
A tournament schedule contains individual matches and also groups of matches like a "group stage," and both respond to the same query — "what’s the total duration?" — where a single match returns its own time and a group sums its children’s times recursively. The scheduling software never needs to special-case whether it’s looking at one match or a whole stage. That is the Composite pattern: individual items and groups of items share one interface, and operations on a group simply delegate to its children.
Step-by-Step Explanation
Step 1
Define a common component interface
Declare the operations both individual objects and groups must support.
Step 2
Implement the leaf
A leaf class implements the interface directly, with no children.
Step 3
Implement the composite
A composite class implements the interface and holds a collection of child components.
Step 4
Delegate recursively
The composite's operations loop over children and call the same interface method on each, recursing naturally.
What Interviewer Expects
- A clear tree-structure / part-whole example
- Understanding that leaf and composite share the same interface
- Recognition that this eliminates type-checking branches in client code
- Awareness of the recursive nature of composite operations
Common Mistakes
- Adding child-management methods (add/remove) only to the composite but calling them on the shared interface unsafely from leaves
- Confusing Composite with Decorator (Composite models part-whole trees; Decorator adds responsibilities to a single object)
- Forgetting that operations must recurse, not just iterate one level deep
- Not handling cycles or infinite recursion in malformed tree structures
Best Answer (HR Friendly)
“The Composite pattern lets you treat a single object and a group of objects the same way, through one shared interface. It’s how you model tree structures like folders and files or org charts, so operations like 'get total size' work identically whether you’re looking at one item or an entire nested structure.”
Code Example
interface FileSystemComponent {
int getSize();
}
class File implements FileSystemComponent {
private int size;
File(int size) { this.size = size; }
public int getSize() { return size; }
}
class Folder implements FileSystemComponent {
private java.util.List<FileSystemComponent> children = new java.util.ArrayList<>();
void add(FileSystemComponent component) { children.add(component); }
public int getSize() {
int total = 0;
for (FileSystemComponent child : children) {
total += child.getSize(); // recurses through leaves and sub-folders alike
}
return total;
}
}
Folder root = new Folder();
root.add(new File(100));
Folder sub = new Folder();
sub.add(new File(50));
root.add(sub);
System.out.println(root.getSize()); // 150, computed uniformlyFollow-up Questions
- How does the Composite pattern differ from the Decorator pattern?
- How would you prevent adding a child to a leaf node safely?
- What real-world APIs (e.g. GUI toolkits) use Composite for their component trees?
- How does Composite interact well with the Visitor pattern for tree traversal?
MCQ Practice
1. The Composite pattern is designed to model?
Composite represents tree structures where individual objects and groups share the same interface.
2. In Composite, how does a composite node typically implement an interface operation?
A composite loops over its children and invokes the same operation on each, recursing naturally through the tree.
3. What is the key benefit of leaf and composite sharing the same interface?
A uniform interface lets clients call the same methods regardless of whether they hold a leaf or a composite.
Flash Cards
Composite pattern in one line? — Composes objects into tree structures so leaves and groups share one interface.
What does a composite's operation typically do? — Recursively delegates the call to each child.
Key benefit? — Client code treats individual objects and groups uniformly, no type-checking branches.
Composite vs Decorator? — Composite models part-whole trees; Decorator adds responsibilities to a single object.