Composite

Intermediate · 14 min read · Low-Level Design, Structural Patterns

Treating trees of objects and single objects uniformly.

The idea in plain words

When things nest inside other things (folders inside folders, boxes inside boxes), give the single item and the group the same interface. Then the code that uses them never has to ask "is this one thing or a group?"

The problem

An e-commerce order can contain products, and bundles — and bundles can contain products and other bundles (a "home office kit" containing a "desk set" bundle). To compute the total price, naive code must check types at every level:

The solution

Give leaves and containers a common interface. Containers implement operations by delegating to their children and combining the results.

Design decision: where do child-management methods live?

Most modern Java code chooses safety (as above). Mention the trade-off if asked.

Real-world uses

Pitfalls

Pros and cons

Related patterns

Interview questions

  • How would you model a file system where you can compute the size of any folder?
  • Composite vs Decorator — both use recursive composition. What's the difference?

Further reading

Key takeaways

  • Composite lets leaves and containers share an interface so trees are processed uniformly.
  • Containers delegate to children and combine results — recursion lives in the structure.
  • Choose safety (child methods only on composites) over transparency in typed languages.
  • Guard against cycles and very deep recursion.

Previous: Proxy · Next: Bridge