When dealing with Tree-structured data, programmers often have to discriminate between a leaf-node and a branch.
The solution is an interface that allows treating complex and primitive objects uniformly. In object-oriented programming,
a composite is an object designed as a composition of one-or-more similar objects, all exhibiting similar functionality.
This is known as a "has-a" relationship between objects.
The key concept is that you can manipulate a single instance of the object just as you would manipulate a group of them.
The operations you can perform on all the composite objects often have a least common denominator relationship.
For example, if defining a system to portray grouped shapes on a screen, it would be useful to define resizing a group of shapes
to have the same effect (in some sense) as resizing a single shape.
The following lists the benefits of using the Composite pattern:
- Defines class hierarchies consisting of primitive objects and composite objects
- Makes it easier to add new kinds of components
- Provides flexibility of structure and a manageable interface
You should use the Composite pattern when:
- You want to represent the whole hierarchy or part of the hierarchy of objects.
- You want clients to be able to ignore the difference between compositions of objects and individual objects.
- The structure can have any level of complexity, and is dynamic.