Composite#

The Composite pattern is a structural design pattern that allows you to compose objects into tree structures to represent part-whole hierarchies. This pattern lets clients treat individual objects and compositions of objects uniformly.

In layman’s terms, imagine a company where you have employees and managers. Managers can have their own employees, and those employees can be managers of other employees. The Composite pattern allows you to treat both employees and managers uniformly, so you can perform operations on them without worrying whether you’re dealing with a simple employee or a manager with a team.

UML Diagram#

    +-------------------+
    |     Component     |
    |-------------------|
    | +operation()      |
    +-------------------+
            ^
            |
    +-------+-----------+
    |                   |
+---+-------+       +---+-------+
| Leaf      |       |Composite  |
|-----------|       |-----------|
|operation()|       |operation()|
+-----------+       |add()      |
                    |remove()   |
                    |getChild() |
                    +-----------+
--- Java Example ---
--- Python Example ---