Design Patterns    |     Security    |     Testing    |     Distributed Computing    |     Contact

Composite

Definition

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

Class Diagram

Composite

Participants

  • Component
    • declares the interface for objects in the composition.
    • implements default behavior for the interface common to all classes, as appropriate.
    • declares an interface for accessing and managing its child components.
    • (optional) defines an interface for accessing a component's parent in the recursive structure, and implements it if that's appropriate.
  • 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.

Benefits

  • Define class hierarchies consisting of primitive objects and composite objects.
  • Makes it easier to add new kind of components.
  • Provides flexibility of structure and manageable interface.

Usage

  • When you want to represent the whole hierarchy or a part of the hierarchy of objects.
  • When you want clients to be able to ignore the differences between compositions of objects and individual objects.
  • When the structure can have any level of complexity andis dynamic.