design patterns ·

Composite

Composes objects into tree structures to represent part-whole hierarchies, treating individual objects and compositions uniformly.

easy0.5hgeneraljava
Ask GPTConfidence

Theory

Explanation

Intuition first, formal definition second. Skim the bullets if you already know this; read the prose if you don't.

When you have a tree structure where both individual items and groups of items should be treated the same way, Composite gives them a shared interface so client code does not need to distinguish between leaves and containers.

A Component interface defines operations for both leaves and composites. Leaf implements Component directly. Composite implements Component and holds a list of child Components. Operations recursively delegate to children.

When to use

File systems, UI component trees, organization charts, menu systems, expression trees - any recursive tree where leaves and containers share behavior.

When not to

When tree depth is always 1 (flat list) - use a simple collection instead.

Key insights

  • The key insight is uniform treatment: client calls display() on a file or a folder - same code path
  • Composite is self-similar: a Composite is a Component that contains Components
  • Common in UI frameworks: a Panel contains Buttons and other Panels
  • Visitor pattern is often used alongside Composite to perform operations on the tree