About Us Contact Us Write for Us Advertise
Home > System Design > Low-Level Design > Composite Pattern in Java (Tree Structures)
System Design › Low-Level Design

Composite Pattern in Java (Tree Structures)

The Composite pattern explained: treat individual objects and groups of objects uniformly through one interface, for tree / part-whole structures like file systems and UI trees. Java code, UML, when to use.

Shiv Pandey
Shiv Pandey
Oct 21, 2026 | 78 views
Composite Pattern in Java (Tree Structures)

🟠 Design Patterns · Structural · Senior

The Composite pattern lets you treat a group of objects the same way you treat a single object. Think of a file system: a file has a size, and a folder also has a size (the sum of its contents) — and a folder can contain files and other folders. Composite is the pattern for these tree structures, where you want to call the same method on a leaf or a whole branch without caring which it is.

In one line: Composite arranges objects into tree structures and lets clients treat individual objects (leaves) and compositions of objects (branches) uniformly through one common interface.

The problem

You're modelling a file system. A File has a getSize(). A Folder also needs getSize() — but its size is the total of everything inside, which may be files or more folders, nested arbitrarily deep. Without a pattern, your code is full of "is this a file or a folder?" checks and manual recursion everywhere. Ugly and error-prone.

The solution: one interface for leaf and branch

🟠 Define a common Component interface that both the leaf and the container implement. The container (composite) holds a list of children — each itself a Component — and implements operations by delegating to its children:

interface FileComponent { int getSize(); }         // common interface

class File implements FileComponent {                // leaf
    private final int size;
    File(int size){ this.size = size; }
    public int getSize(){ return size; }
}
class Folder implements FileComponent {              // composite
    private final List<FileComponent> children = new ArrayList<>();
    public void add(FileComponent c){ children.add(c); }
    public int getSize() {                            // sum of children
        return children.stream().mapToInt(FileComponent::getSize).sum();
    }
}
// build a tree and treat it uniformly:
Folder root = new Folder();
root.add(new File(100));
Folder sub = new Folder(); sub.add(new File(50));
root.add(sub);
root.getSize();   // 150 — recurses automatically
Folder (root) File 100 Folder (sub) File 50 getSize() = 150

The magic: root.getSize() works whether the tree is one file or a thousand nested folders. Leaves return their own size; composites recurse into children. The client calls getSize() uniformly and never checks "file or folder?"

Where it fits

🟠 Composite is the natural pattern for anything shaped like a tree / part-whole hierarchy:

  • File systems — files and folders (the classic).
  • UI toolkits — a button is a component, and a panel containing components is also a component; render() works on both.
  • Org charts — an individual employee and a manager (with reports) both answer "total headcount."
  • Graphics — a shape and a group of shapes both support draw() and move().

The key benefit

Client code becomes simple and uniform — no type-checking, no special-casing groups. And the structure is naturally extensible: adding a new kind of leaf just means implementing the component interface, and it drops into any tree. The recursion that would otherwise clutter your client is pushed into the composite where it belongs.

When to use it

Use Composite when you have (or can model) a part-whole tree and you want clients to treat individual and grouped objects the same way. If your data isn't hierarchical, this pattern doesn't apply. The tell-tale sign: "I want to call the same operation on one thing or a group of things and have it just work recursively."

The interview-ready summary

"Composite models tree / part-whole structures so clients treat a single object and a group of objects uniformly. Both the leaf and the container implement one Component interface; the container holds child components and implements operations by recursing into them. So getSize() on a folder sums its contents automatically, however deeply nested. It removes 'is this one or many?' checks from client code. Classic uses: file systems, UI component trees, org charts." That names the intent, the mechanism, and clean examples."

What to read next

← Proxy pattern · Strategy pattern →

Related Articles

Chain of Responsibility Pattern in Java (Example)
System Design › Low-Level Design

Chain of Responsibility Pattern in Java (Example)

Template Method Pattern in Java (with Example)
System Design › Low-Level Design

Template Method Pattern in Java (with Example)

Command Pattern in Java (with Undo Example)
System Design › Low-Level Design

Command Pattern in Java (with Undo Example)

State Pattern in Java (with Example)
System Design › Low-Level Design

State Pattern in Java (with Example)