Skip to main content

What problem does the Composite pattern solve?

The Composite pattern solves the problem of working with hierarchical object structures: it lets you treat individual objects and groups of them uniformly, as if they were the same thing.


1. The Essence of the Problem

In many systems, objects form tree-like structures: for example, files and folders, UI elements, organizational units. Client code has trouble telling a leaf (a single object) apart from a container (a composite object). Without the pattern, you have to write different code for each case:

java
if (obj instanceof Folder) { ... } else if (obj instanceof File) { ... }

This violates the open/closed principle and makes the code inflexible.


2. What Composite Does

Composite introduces a common interface for all tree elements (both simple and composite ones). Now the client works with them the same way, without caring what they are made of.


3. What It Looks Like

  • Component - a common interface for all elements (for example, render(), getSize()).
  • Leaf - an element with no child objects (for example, a file).
  • Composite (container) - an element that holds other Component objects and implements their methods by delegating operations to its children.

Example (Java):

java
interface Graphic { void draw(); } class Dot implements Graphic { public void draw() { System.out.println("Draw dot"); } } class CompoundGraphic implements Graphic { private List<Graphic> children = new ArrayList<>(); public void add(Graphic child) { children.add(child); } public void draw() { for (Graphic g : children) g.draw(); } }

Now the client can call:

java
Graphic group = new CompoundGraphic(); group.add(new Dot()); group.add(new Dot()); group.draw(); // Draws the group and the dots the same way

4. The Problem It Solves

Composite removes the need to distinguish between "single" and "composite" objects. It lets you:

  • access the tree of objects through a single interface;
  • process everything the same way, regardless of structure;
  • easily add new element types without changing client code.

5. Conclusion

The Composite pattern solves the problem of managing hierarchical objects by providing a single interaction interface for elements and their groups. The result is code that is simple, extensible, and independent of the tree's structure.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.