Structural Patterns • Composite PatternEasy⏱️ ~2 min
What is the Composite Pattern?
Definition
Composite Pattern is a structural design pattern that lets you compose objects into tree structures to represent part-whole hierarchies. It allows clients to treat individual objects and compositions of objects uniformly through a common interface.
The pattern solves the problem of treating individual objects (leaf nodes) and groups of objects (composite nodes) differently. Without this pattern, clients must check object types and handle leaves and composites with separate logic, leading to brittle code.
Core Problem Solved:
When you have hierarchical data (trees), you need to perform operations that work the same way whether applied to a single element or a group of elements. Examples include file systems (files and folders), organizational charts (employees and departments), or UI components (buttons and panels).
Key Insight: The pattern makes the tree structure transparent to clients. A client calling operation() on a leaf or composite uses identical code, with the composite delegating to its children.
Interview Tip: Emphasize that this pattern is about uniform treatment, not just building trees. Many structures are hierarchical, but Composite is specifically for when operations should work identically on parts and wholes.
💡 Key Takeaways
✓Composes objects into tree structures representing part-whole hierarchies
✓Treats individual objects (leaves) and compositions (composites) uniformly
✓Clients interact through a common interface, unaware of object complexity
✓Simplifies client code by eliminating type-checking and branching logic
✓Classic examples: file systems, graphic shapes, organization hierarchies
📌 Examples
1File system: treat a File and a Folder identically when calculating size
2Graphics editor: move a single Shape or a Group of shapes with same operation
3Menu system: execute on MenuItem or SubMenu without checking type