Want to represent part-whole hierarchies of objects
Want clients to be able to ignore the difference between compositions of objects and individual objects, as clients treat all objects in the composite structure uniformly
Composite: Structure
Composite: Participants
Component (e.g., Graphic)
Declares the interface for objects in the composition
Implements the default behavior for the interface common to all classes as appropriate
Declares an interface for accessing and managing its child components
Optionally defines an interface for accessing a component’s parent
Client
Manipulates objects in the composition through the Component interface
Composite: Object Participants
Leaf (e.g., Rectangle, Line, Text, etc.)
Represents leaf object (leaves have no children) in the composition
Defines behavior for primitive objects in the composition
Composite (e.g., Picture)
Defines behavior for components having children
Stores child components
Implements child-related operations in the Component interface
Composite: Collaborations
Clients use the Component class interface to interact with objects in the composite structure:
If the recipient is a Leaf, then the request is handled directly
If the recipient is a Composite, it usually forwards requests to its child components, possibly performing additional operations before and after forwarding.
Composite: Consequences
A class hierarchy of primitive and composite objects that permits recursive structures
Clients are simple as they handle primitive and composite objects in the same way
Can add new kinds of components, both Composite or Leaf, that work automatically with existing client code
However, being able to add any Component type can make the design overly general
Composite #1: Design
Composite #1: Usage
Composite UML
Composite #2: Design
Composite #2: Usage
Implementation Issues
Storing parent references
Sharing components
Size and contents of Composite interface, e.g., traversing children
Child management
Should Component implement a list of Components?
Child ordering
Caching to improve performance
Who should delete components?
What's the best data structure for storing components?
Related Patterns
Composite
Used to implement MacroComposites
Memento
Stores the state the Composite requires for an undo