Composite

Composite

Intent

Compose objects into tree structures to represent part-whole hierarchies. Composite clients treat individual objects and compositions of objects uniformaly.

Applicability

Use the Composite pattern when:

  • You want to represent part-whole hierarchies of objects.
  • You want clients to be able to ignore the difference between compositions of objects and invidual objects. Clients will treat all objects in the composite structure uniformly.

Structure

Orange

Participants

  • Component: declares the interface for objects in the composition, implements default behavior for the interface common to all classes, declares an interface for accessing and managing it's child components.
  • 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.

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, then it usually forwards requests to it's child components, possible performing additional operations before and/or after forwarding.

Consequences

The composite pattern:

  • defines class hierarchies consisting of primitive objects and composite objects. Wherver client code expects a primitive object, it can also take a composite object.
  • makes the client simple. Clients can treat composite structures and individual objects uniformly.
  • makes it easier to add new kinds of components. Newly defined Composite or Leaf subclasses work automatically with existing structures and client code.
  • can make your design overly general.

Sample Code

Composite

Related Patterns

  • Often the component-parent link is used for a Chain Of Responsibility.
  • Decorator is often used with Composite. When decorators and composites are used together, they will usually have a common parent class. So decorators will have to support the Component interface with operations like Add, remove, getchild.
  • Flyweight lets you share components, but they can no longer refer to their parents.
  • Iterator can be used to traverse composites.
  • Visitor localizes operations and behaviour that would otherwise be distributed across Composite and Leaf classes.