Real World Example
Every organization is composed of employees. Each of the employees has the same features i.e. has a salary, has some responsibilities, may or may not report to someone, may or may not have some subordinates etc.
In Plain Words
Composite pattern lets clients treat the individual objects in a uniform manner.Wikipedia Definition
In software engineering, the composite pattern is a partitioning design pattern. The composite pattern describes that a group of objects is to be treated in the same way as a single instance of an object. The intent of a composite is to “compose” objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.
Programmatic Example
Taking our employees example from above. Here we have different employee types:Key Participants
Component
Component
Declares the interface for objects in the composition (in our example:
Employee interface)Leaf
Leaf
Represents leaf objects in the composition that have no children (in our example:
Developer, Designer)Composite
Composite
Defines behavior for components having children and stores child components (in our example:
Organization)Client
Client
Manipulates objects in the composition through the Component interface
Structure Visualization
When to Use?
Use the Composite pattern when:
- You want to represent part-whole hierarchies of objects
- You want clients to ignore the difference between compositions of objects and individual objects
- The structure can have any level of complexity and is dynamic
- You need to treat individual objects and compositions uniformly
Benefits
- Simplicity: Clients can treat composite structures and individual objects uniformly
- Easier to Add New Components: New component types can be added without changing existing code
- Flexibility: Makes it easier to add new kinds of components
Considerations
Real-World Applications
- File systems (files and folders)
- GUI components (containers and widgets)
- Organization hierarchies (employees and departments)
- Graphics rendering (shapes and groups of shapes)
Related Patterns
- Decorator: Often used together with Composite. When decorators and composites are used together, they will usually have a common parent class
- Iterator: Can be used to traverse composite structures
- Visitor: Can be used to apply an operation over a composite structure