Structural Patterns • Composite PatternMedium⏱️ ~2 min
Composite Pattern Structure and Participants
The Composite Pattern consists of three core participants that work together to create a tree structure with uniform operations.
«interface»
Component
+ operation(): void
+ add(Component): void
+ remove(Component): void
+ getChild(int): Component
▲
Leaf
+ operation(): void
Composite
- children: List<Component>
+ operation(): void
+ add(Component): void
+ remove(Component): void
Participant Responsibilities:
1. Component (interface or abstract class):
Declares the common interface for both leaf and composite objects. Defines default behavior for management operations (
Declares the common interface for both leaf and composite objects. Defines default behavior for management operations (
add(), remove(), getChild()) when appropriate. May throw exceptions in leaf implementations if management operations are not supported.2. Leaf (concrete class):
Represents end objects in the composition with no children. Implements
Represents end objects in the composition with no children. Implements
operation() to perform actual work. Management methods (add(), remove()) typically throw UnsupportedOperationException or return error, since leaves cannot have children.3. Composite (concrete class):
Stores child components in a collection (List, Set, or Array). Implements
Stores child components in a collection (List, Set, or Array). Implements
operation() by delegating to all children, then possibly performing its own work. Implements management methods to add, remove, and access children.Interview Tip: Discuss whether to put
add()/remove() in Component or only in Composite. Putting them in Component prioritizes transparency (treating all objects uniformly) over safety. Putting them only in Composite prioritizes type safety but requires clients to know object types.Recursive Nature: The operation() in Composite typically iterates through its children and calls operation() on each. This creates a recursive traversal of the tree structure, automatically handling any depth of nesting.
💡 Key Takeaways
✓Component interface defines uniform operations for both leaves and composites
✓Leaf implements operations directly without delegation
✓Composite delegates operations to child components recursively
✓Tree structure is transparent to clients through common interface
✓Design decision: whether to include child management in Component or only Composite
📌 Examples
1Component = FileSystemNode, Leaf = File, Composite = Directory
2Component = GraphicObject, Leaf = Circle, Composite = Group
3Component = MenuComponent, Leaf = MenuItem, Composite = Menu