Compose object intot tree structures to represent part-whole hierachies. Composite lets client treat individual objects and compositions of objects uniformly.
Graphics application like drawing editors and schematic capture systems let user build complex diagrams out of simple components. The user can group components to form larger components, which in turn can be grouped to form still larger components.
But there’s a problem with this approach: Code the uses these classes must treat primitive and container objects differently, even if most of time the user treats them identical. Having to distinguish theses objects makes the application more complex. The composite pattern describes how to use recursive composition so that clients don’t have to make this distincation.
The key to the Composite pattern is an abstract class that represents both primitives and their containers.
Use the composite pattern when
- We want to represent part-whole hierachies og objects.
- We want client to ignore compostion objecst and individual objects. Client will treat all object in compostion uniformaly.
A typical Composite object structure might look like this: