The Composite Pattern is a structural design pattern that lets you treat individual objects and groups of objects uniformly which means you can compose objects into tree structures and then work with these structures as if they were individual objects.
Think of it like a tree structure where both leaves (single objects) and branches (groups of objects) can be handled the same way. This is helpful when building systems with hierarchical data, like UI components or file systems.
- Component: A common interface or abstract class for all objects in the hierarchy.
- Leaf: A basic, indivisible object that implements the
Component
interface. - Composite: A container object (or branch) that also implements the
Component
interface and can hold otherComponent
objects (both Leafs and other Composites). - Tree Stucture: Underlying entity represented via tree structure (parent - child heirarchy)
- Uniformity: The ability to treat both Leafs and Composites the same way via the
Component
interface.
- Frontend Frameworks: Building UI trees with components (e.g., React's virtual DOM and component composition model where both leaf components and container components share the same basic interface)
- Query Builders: Representing complex database query structures.
- Filesystem Operations: Representing files (Leaf) and directories (Composite).
- Image Editors: Handling shapes (Leaf) and groups of shapes (Composite).