Codacoda
Back to Academy

design patterns

Composite

The Composite pattern composes objects into tree structures to represent part-whole hierarchies. It lets clients treat individual objects and compositions of objects uniformly. The key participants are the Component (declares the interface for objects in the composition), Leaf (represents end objects with no children), and Composite (stores child components and implements child-related operations). Think of a file system: files are leaves and folders are composites — both can be 'opened,' and a folder can contain files and other folders. Use Composite when you want clients to be able to ignore the difference between compositions of objects and individual objects, such as in UI component trees, organization charts, or menu structures.

Use Cases

  • File system representations (files and directories)
  • UI component trees (panels containing buttons and other panels)
  • Organization charts (departments containing teams and employees)
  • Menu systems with nested sub-menus

Visualization

children<<interface>>Component+operation()Leaf+operation()Composite+operation()+add()+remove()Child LeafChild Comp.
Speed:1x
Composite — composes objects into tree structures to treat individual and composite objects uniformlyStep 1 / 7

Implementation

Output

Click "Run Code" to see output...