Composite

structural

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

Intent

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

Motivation

When you want to represent part-whole hierarchies of objects and you want clients to be able to ignore the difference between compositions of objects and individual objects, the Composite pattern is useful.

Structure

The pattern involves a Component interface that declares operations common to both simple and complex objects. Leaf classes represent end objects with no children. Composite classes represent complex components that may have children.

Participants

  • Component - declares the interface for objects in the composition
  • Leaf - represents leaf objects in the composition with no children
  • Composite - defines behavior for components having children and stores child components
  • Client - manipulates objects in the composition through the Component interface

Pros

  • Defines class hierarchies with primitive and composite objects
  • Makes it easier to add new kinds of components
  • Provides flexibility of structure
  • Follows Open/Closed Principle

Cons

  • Can make the design overly general
  • Difficult to restrict components of a composite

Use Cases

File system hierarchies
GUI component trees
Organization structures
Graphics scene graphs
Menu systems

Implementation Tips

Considerations

  • Decide where to define child management operations
  • Consider using Component reference for parent
  • Think about ordering of children
  • Consider caching for performance

Tips

  • Keep the Component interface focused
  • Use type checking carefully when needed
  • Consider iterator pattern for traversing
  • Document the tree structure clearly

Interactive Code Editor

Related Patterns