Composite pattern is used to separate abstraction from its implementation so that both can be modified independently.
Composite pattern is used when we need to treat a group of objects and a single object in the same way. Composite pattern composes objects in term of a tree structure to represent part as well as whole hierarchies. This pattern creates a class contains a group of its own objects. This class provides ways to modify its group of the same objects.
A visualization of the classes and objects participating in this pattern.
-
Component
- declares the interface for objects in the composition.
- implements default behavior for the interface common to all classes, as appropriate.
- declares an interface for accessing and managing its child components.
- (optional) defines an interface for accessing a component's parent in the recursive structure, and implements it if that's appropriate.
-
Leaf
- represents leaf objects in the composition. A leaf has no children.
- defines behavior for primitive objects in the composition.
-
Composite
- defines behavior for components having children.
- stores child components.
- implements child-related operations in the Component interface.
-
Client
- manipulates objects in the composition through the Component interface.
