Composite Pattern

The Composite pattern organizes objects into tree structures, making them work together like one. It lets clients treat individual objects and compositions of objects in a similar way.

This is useful when dealing with things organized in a tree-like structure, such as files and folders in a computer’s file system.

Key Participants:

  • Component: This is the base interface or abstract class that declares the common operations for both leaf objects and composite objects. It defines methods for accessing, manipulating, and iterating through child components.
  • Leaf: Leaf objects are the individual objects that don’t have any child components. They implement the operations defined in the Component interface.
  • Composite: Composite objects are containers that can hold child components. They implement the operations defined in the Component interface but also manage a collection of child components.
  +------------------+
  |     Component    |
  +------------------+
          /   \
         /     \
+-------+    +-----------+
|  Leaf |    | Composite |
+-------+    +-----------+
classDiagram
  class Component {
    +operation()
    +add(Component c)
    +remove(Component c)
    +getChild(int index)
  }

  class Leaf {
    +operation()
  }

  class Composite {
    +operation()
    +add(Component c)
    +remove(Component c)
    +getChild(int index)
  }

  Component <|-- Leaf
  Component <|-- Composite

Examples

Files and Folders

classDiagram
  class FileSystemComponent {
    +getName()
    +displayInfo()
  }

  class File {
    +getName()
    +displayInfo()
  }

  class Folder {
    +addComponent(FileSystemComponent component)
    +removeComponent(FileSystemComponent component)
    +displayInfo()
  }

  FileSystemComponent <|-- File
  FileSystemComponent <|-- Folder

Employees and Departments

classDiagram
  class Employee {
    +getName()
    +getRole()
    +displayInformation()
  }

  class IndividualEmployee {
    +getName()
    +getRole()
    +displayInformation()
  }

  class Department {
    +addEmployee(Employee employee)
    +removeEmployee(Employee employee)
    +displayInformation()
  }

  Employee <|-- IndividualEmployee
  Employee <|-- Department

Menu Item and Menu Category

classDiagram
  class MenuItem {
    +getName()
    +getPrice()
    +display()
  }

  class Dish {
    +getName()
    +getPrice()
    +display()
  }

  class MenuCategory {
    +addItem(MenuItem item)
    +removeItem(MenuItem item)
    +display()
  }

  MenuItem <|-- Dish
  MenuItem <|-- MenuCategory