The Composite pattern is used when we need to treat both a group of items and a single object in the same manner. The composite pattern arranges elements in a tree structure to show both partial and complete hierarchies.
Example of Composite Design Pattern
Examples of composite patterns are:
File System Folders
Managers and Employees
Assemblies
Composite Design pattern with UML diagram
The UML class diagram above includes the following classes, interfaces, and objects:
Component: This is an abstract class whose members will be implemented by all objects in the hierarchy. It serves as the root class for every object in the hierarchy.
Composite: This class offers methods for adding, removing, finding, and getting child components.
Leaf: This class is used to define leaf components within the tree structure, hence they cannot have children.
When to use Composite Design Patterns?
The composite design pattern is useful for creating hierarchical representations of objects.
A single item and a collection of objects should be handled the same.
The Composite pattern is used when data is organized in a tree structure (similar to computer directories).