SyntaxPilot
Courses/Low-Level Design/Lesson 32
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Low-Level Design · Lesson 32 of 90

Composite pattern

Composite patterncomponentleafcompositetree structurespart-whole hierarchyuniform treatmentrecursive operationstransparency vs safety trade-offfile-system examplemenu example

These are the notes for Low-Level Design (LLD) episode 32, the sixth structural pattern. Some data is shaped like a tree: folders inside folders, menus inside menus, teams inside departments. The Composite pattern lets your code treat one single thing and a whole group of things in exactly the same way. We start with a Diwali gift hamper, watch Priya's storage screen report a folder as 1,300 MB when it really holds 3,300 MB, and then invent the composite. Every program was actually run with javac Main.java && java -cp . Main (Java 21). Outputs are real.

1. The real-life idea: a gift hamper

A Diwali gift hamper In code
A box of sweets: has a price, holds nothing else A leaf: a single object with no children
A box of boxes: dry fruits, sweets, a smaller box of chocolates A composite: an object that holds other objects
"What's the price?" asked of a single box or the whole hamper, the same way The component: one shared interface for both
The hamper asks each box inside; each inner box asks its own insides Recursion: a method that calls the same method on smaller parts

2. The problem: folders inside folders

Priya's storage screen shows how much space each folder takes. First try: a Folder holds a List<File>.

import java.util.*;

class File {
    final String name; final int mb;
    File(String name, int mb) { this.name = name; this.mb = mb; }
}
class Folder {
    final String name; final List<File> files = new ArrayList<>();
    Folder(String name) { this.name = name; }
    void add(File f) { files.add(f); }
    int size() { int total = 0; for (File f : files) total += f.mb; return total; }
}
public class Main {
    public static void main(String[] args) {
        Folder photos = new Folder("Photos");
        photos.add(new File("diwali.jpg", 300));
        Folder trip = new Folder("Goa trip");
        trip.add(new File("beach.mp4", 1000));
        photos.add(trip);                                  // a folder inside a folder
        System.out.println("Photos: " + photos.size() + " MB");
    }
}
Main.java:19: error: incompatible types: Folder cannot be converted to File
        photos.add(trip);                                  // a folder inside a folder
                   ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

A real folder can hold another folder, but a List<File> only accepts files. Folder is not a File, so this doesn't even compile. (A compile error is found by javac before the program runs.)

The quick hack: List<Object> and instanceof

Object is the parent of every class in Java, so a List<Object> accepts anything. Then size() asks each item "what are you?" with instanceof (true if an object is of a given type; o instanceof File f also gives you f, a File variable, from Java 16 on: pattern matching for instanceof, episode 9).

import java.util.*;
class File {
    final String name; final int mb;
    File(String name, int mb) { this.name = name; this.mb = mb; }
}
class Folder {
    final String name; final List<Object> items = new ArrayList<>();      // files OR folders
    Folder(String name) { this.name = name; }
    void add(Object o) { items.add(o); }
    int size() { int total = 0;
        for (Object o : items) {
            if (o instanceof File f) total += f.mb;
            else if (o instanceof Folder sub)                               // one level down...
                for (Object o2 : sub.items) if (o2 instanceof File f2) total += f2.mb;
        }
        return total;
    }
}
public class Main {
    public static void main(String[] args) {
        Folder photos = new Folder("Photos"), trip = new Folder("Goa trip"), day1 = new Folder("Day 1");
        photos.add(new File("diwali.jpg", 300));
        photos.add(trip);  trip.add(new File("beach.mp4", 1000));
        trip.add(day1);    day1.add(new File("sunset.mp4", 2000));           // two levels down
        photos.add("notes.txt");                                            // a String sneaks in
        System.out.println("Photos: " + photos.size() + " MB   (real: 3300 MB)");
    }
}
Photos: 1300 MB   (real: 3300 MB)

Wrong by 2,000 MB. size() only looks one level down, so the 2,000 MB video inside Day 1 (two levels down) is missing. And the String "notes.txt" was accepted and silently ignored.

Why it failed

  • List<File> can't hold a folder: compile error.
  • List<Object> + instanceof handles each depth by hand; the next level down is always missed.
  • Object accepts anything, so wrong items slip in with no error.
  • What we want: ask any item its size the same way, and let each folder add up its own children.

3. The shape of the data: a tree

A tree is data with one item at the top, the root (Photos), where every item can have items under it, its children. It can be any number of levels deep.

Photos/                  <- root, a composite
├── diwali.jpg   300     <- leaf
└── Goa trip/            <- composite
    ├── beach.mp4   1000 <- leaf
    └── Day 1/           <- composite
        └── sunset.mp4  2000

The items at the ends (no children) are leaves: files. Items with children are composites: folders. A structure where a whole (a folder) is made of parts that may themselves be wholes is a part-whole hierarchy.

4. The fix: one interface for leaves and composites

import java.util.*;
interface Item { int size(); void print(String indent); }       // component
class File implements Item {                                 // leaf
    private final String name; private final int mb;
    File(String name, int mb) { this.name = name; this.mb = mb; }
    public int size() { return mb; }
    public void print(String indent) { System.out.println(indent + name + "  " + mb + " MB"); }
}
class Folder implements Item {                               // composite
    private final String name; private final List<Item> children = new ArrayList<>();
    Folder(String name) { this.name = name; }
    Folder add(Item i) { children.add(i); return this; }
    public int size() { int total = 0; for (Item c : children) total += c.size(); return total; }
    public void print(String indent) {
        System.out.println(indent + name + "/  " + size() + " MB");
        for (Item c : children) c.print(indent + "    ");
    }
}
public class Main {
    public static void main(String[] args) {
        Folder day1 = new Folder("Day 1").add(new File("sunset.mp4", 2000));
        Folder trip = new Folder("Goa trip").add(new File("beach.mp4", 1000)).add(day1);
        Folder photos = new Folder("Photos").add(new File("diwali.jpg", 300)).add(trip);
        photos.print("");
        Item one = new File("selfie.jpg", 5);                 // a single file, same calls
        System.out.println("selfie: " + one.size() + " MB; whole Photos: " + photos.size() + " MB");
    }
}
Photos/  3300 MB
    diwali.jpg  300 MB
    Goa trip/  3000 MB
        beach.mp4  1000 MB
        Day 1/  2000 MB
            sunset.mp4  2000 MB
selfie: 5 MB; whole Photos: 3300 MB
  • Item is the component: the shared interface with size() and print(indent).
  • File is the leaf: its size is just its own megabytes.
  • Folder is the composite: it holds a List<Item>, so a child can be a file or a folder, and nothing else (a String won't compile).
  • Folder.size() asks every child for its size and adds them up. It never asks "what are you?". If the child is a folder, its size() does the same for its own children, all the way down. That's recursion, and it handles any depth.
  • print works the same way, adding four spaces of indent per level.
  • add returns this (the folder itself), so calls can be chained: new Folder("Goa trip").add(a).add(b).

The last line shows uniform treatment: a single selfie and the whole Photos folder answer the same size() call. The client never needs instanceof.

How the sum flows

  1. photos.size() asks its children.
  2. Goa trip asks its children; Day 1 asks sunset.mp4, a leaf, which answers 2000. So Day 1 = 2000.
  3. Goa trip = 1000 + 2000 = 3000.
  4. Photos = 300 + 3000 = 3300.

The answers flow back up the tree. Each folder only ever looks at its own children.

5. It has a name: the Composite pattern

Intent (Gang of Four wording): "Compose objects into tree structures to represent part-whole hierarchies." Composite lets clients treat individual objects and compositions of objects uniformly (the same way).

Role Meaning In our code
Component The shared interface for everything in the tree Item, MenuPart
Leaf An object with no children File, Dish
Composite An object that holds children (components) and passes work down to them Folder, Menu
Client Code that uses the tree only through the component the storage screen

The key trick: a composite is a component (implements Item) and has components (List<Item> children). Being one and holding many is what allows any depth.

6. Another tree: a restaurant menu

import java.util.*;

interface MenuPart { void show(String indent); int dishes(); }
class Dish implements MenuPart {                                   // leaf
    private final String name; private final int rs;
    Dish(String name, int rs) { this.name = name; this.rs = rs; }
    public void show(String indent) { System.out.println(indent + "- " + name + "  Rs " + rs); }
    public int dishes() { return 1; }
}
class Menu implements MenuPart {                                   // composite
    private final String title; private final List<MenuPart> parts = new ArrayList<>();
    Menu(String title, MenuPart... parts) { this.title = title; this.parts.addAll(List.of(parts)); }
    public void show(String indent) {
        System.out.println(indent + title.toUpperCase());
        for (MenuPart p : parts) p.show(indent + "   ");
    }
    public int dishes() { return parts.stream().mapToInt(MenuPart::dishes).sum(); }
}
public class Main {
    public static void main(String[] args) {
        MenuPart full = new Menu("Sharma Dhaba",
            new Menu("South Indian", new Dish("Masala dosa", 90), new Dish("Idli", 50)),
            new Menu("Drinks", new Dish("Chai", 20),
                new Menu("Cold", new Dish("Lassi", 60), new Dish("Nimbu pani", 30))));
        full.show("");
        System.out.println(full.dishes() + " dishes in total");
    }
}
SHARMA DHABA
   SOUTH INDIAN
      - Masala dosa  Rs 90
      - Idli  Rs 50
   DRINKS
      - Chai  Rs 20
      COLD
         - Lassi  Rs 60
         - Nimbu pani  Rs 30
5 dishes in total
  • MenuPart... parts is varargs ("variable arguments"): the constructor accepts any number of MenuParts, which arrive as an array.
  • dishes() uses a stream (episode 5): mapToInt(MenuPart::dishes) turns each part into its dish count, sum() adds them. A dish counts 1; a menu counts all of its parts.
  • The show code never checks whether something is a dish or a menu.

Other trees you'll meet: an organisation chart (employees and managers), the parts of a car, a page made of UI panels and buttons, an arithmetic expression (2 + 3) * 4.

7. Transparency vs safety: where does add() go?

Safe design Transparent design
Where add() is Only on the composite (Folder) On the component (Item), for everyone
Misuse on a leaf Caught at compile time Found only at runtime (an exception)
Cost To add children you need a Folder reference Leaves carry a method that makes no sense for them

Safe: Item has only size(). A variable declared as Item can't call add:

import java.util.*;

interface Item { int size(); }                                     // SAFE: no add() here
class File implements Item {
    private final int mb; File(int mb) { this.mb = mb; }
    public int size() { return mb; }
}
class Folder implements Item {
    private final List<Item> children = new ArrayList<>();
    void add(Item i) { children.add(i); }                          // only folders have add()
    public int size() { return children.stream().mapToInt(Item::size).sum(); }
}
public class Main {
    public static void main(String[] args) {
        Item photos = new Folder();
        photos.add(new File(300));                                 // photos is typed as Item
        System.out.println(photos.size());
    }
}
Main.java:16: error: cannot find symbol
        photos.add(new File(300));                                 // photos is typed as Item
              ^
  symbol:   method add(File)
  location: variable photos of type Item
1 error

Transparent: Item has a default method (a method body inside an interface, episode 3) add that throws UnsupportedOperationException; Folder overrides it.

import java.util.*;

interface Item {                                                   // TRANSPARENT: add() for everyone
    int size();
    default void add(Item i) { throw new UnsupportedOperationException("a file can't hold other items"); }
}
class File implements Item {
    private final int mb; File(int mb) { this.mb = mb; }
    public int size() { return mb; }
}
class Folder implements Item {
    private final List<Item> children = new ArrayList<>();
    public void add(Item i) { children.add(i); }
    public int size() { return children.stream().mapToInt(Item::size).sum(); }
}
public class Main {
    public static void main(String[] args) {
        Item photos = new Folder();
        photos.add(new File(300));                                 // fine: Item has add()
        System.out.println("Photos: " + photos.size() + " MB");
        Item selfie = new File(5);
        selfie.add(new File(1));                                   // compiles... then?
    }
}
Photos: 300 MB
Exception in thread "main" java.lang.UnsupportedOperationException: a file can't hold other items
    at Item.add(Main.java:5)
    at Main.main(Main.java:22)

An exception is Java's way of reporting a problem while the program runs; if nobody catches it, the program stops and prints it. Neither design is wrong. In Java, prefer safe unless client code really must add children without knowing the type.

8. The trap: a folder inside itself

A tree must have no loops. Add a folder into itself and size() never ends:

import java.util.*;
interface Item { int size(); void print(String indent); }       // component
class File implements Item {                                 // leaf
    private final String name; private final int mb;
    File(String name, int mb) { this.name = name; this.mb = mb; }
    public int size() { return mb; }
    public void print(String indent) { System.out.println(indent + name + "  " + mb + " MB"); }
}
class Folder implements Item {                               // composite
    private final String name; private final List<Item> children = new ArrayList<>();
    Folder(String name) { this.name = name; }
    Folder add(Item i) { children.add(i); return this; }
    public int size() { int total = 0; for (Item c : children) total += c.size(); return total; }
    public void print(String indent) {
        System.out.println(indent + name + "/  " + size() + " MB");
        for (Item c : children) c.print(indent + "    ");
    }
}
public class Main {
    public static void main(String[] args) {
        Folder photos = new Folder("Photos").add(new File("diwali.jpg", 300));
        photos.add(photos);                                   // oops: a folder inside itself
        System.out.println(photos.size());
    }
}
Exception in thread "main" java.lang.StackOverflowError
    at Folder.size(Main.java:13)
    at Folder.size(Main.java:13)
    at Folder.size(Main.java:13)
    at Folder.size(Main.java:13)
    at Folder.size(Main.java:13)
    at Folder.size(Main.java:13)
    at Folder.size(Main.java:13)
    ... (the same line repeats about a thousand times)

Each method call that is still waiting for an answer uses a little memory called the call stack; endless recursion fills it and Java throws StackOverflowError. Fix: in add, refuse the folder itself (and, if you track parents, any of its parents):

Folder add(Item i) {
    if (i == this) throw new IllegalArgumentException("a folder can't contain itself");
    children.add(i); return this;
}

Common mistakes

Mistake Exact message / symptom Why Fix
List<File> for a folder's contents error: incompatible types: Folder cannot be converted to File A folder isn't a file List<Item>, the component
List<Object> + instanceof no error: Photos: 1300 MB (real: 3300 MB) Each depth handled by hand Each folder sums its children's size()
Adding a folder into itself Exception in thread "main" java.lang.StackOverflowError The recursion never ends Check in add(); a tree has no loops
add() on a leaf (transparent design) java.lang.UnsupportedOperationException: a file can't hold other items Leaves have no children Safe design, or check before adding
Calling add on a variable typed Item (safe design) error: cannot find symbol ... symbol: method add(File) Item has no add Keep a Folder reference to build the tree

Mini project: an organisation chart

Build a company tree: an Employee (leaf) has a name and a salary in rupees; a Manager (composite) has a name, a salary and a team of Staff. Print the chart with indentation and the total salary cost under the CEO.

Solution
import java.util.*;

interface Staff { int cost(); void print(String indent); }
class Employee implements Staff {
    private final String name; private final int salary;
    Employee(String name, int salary) { this.name = name; this.salary = salary; }
    public int cost() { return salary; }
    public void print(String indent) { System.out.println(indent + name + "  Rs " + salary); }
}
class Manager implements Staff {
    private final String name; private final int salary; private final List<Staff> team = new ArrayList<>();
    Manager(String name, int salary) { this.name = name; this.salary = salary; }
    Manager add(Staff s) { team.add(s); return this; }
    public int cost() { int total = salary; for (Staff s : team) total += s.cost(); return total; }
    public void print(String indent) {
        System.out.println(indent + name + " (manager)  Rs " + salary);
        for (Staff s : team) s.print(indent + "    ");
    }
}
public class Main {
    public static void main(String[] args) {
        Manager tech = new Manager("Priya", 90000).add(new Employee("Ravi", 50000)).add(new Employee("Asha", 55000));
        Manager ceo = new Manager("Neha", 150000).add(tech).add(new Employee("Kabir", 40000));
        ceo.print("");
        System.out.println("total monthly cost: Rs " + ceo.cost());
    }
}
Neha (manager)  Rs 150000
    Priya (manager)  Rs 90000
        Ravi  Rs 50000
        Asha  Rs 55000
    Kabir  Rs 40000
total monthly cost: Rs 385000

Practice

1. Add int count() that returns how many files a folder holds, at any depth.

Answer

Add int count(); to Item. File.count() returns 1. Folder.count() returns the sum of its children's count(). Same recursion as size().

2. Add Optional<Item> find(String name) that searches the whole tree.

Answer

File.find returns Optional.of(this) if the name matches, else Optional.empty(). Folder.find checks its own name, then calls find on each child and returns the first non-empty result. (Optional is a box that may or may not hold a value, episode 5.)

3. Why is List<Object> worse than List<Item>, even if you handle every depth correctly?

Answer

List<Object> accepts anything (a String slipped in), forces instanceof checks in every operation, and every new kind of item (say Shortcut) means editing every operation. List<Item> lets the compiler reject wrong items and lets each class answer for itself.

4. Safe or transparent: your UI builder code adds children to whatever node the user clicked, without knowing its type.

Answer

Transparent is reasonable here, because the client must call add on any node. Leaves throw UnsupportedOperationException, and the UI can show "this item can't hold others".

5. Is a composite the same as a decorator? Both wrap components.

Answer

No. A decorator (episode 28) wraps one component to add behaviour, and looks like it. A composite holds many children to represent a whole made of parts. Structure is similar; intent is different.

Quick quiz

Folder a = new Folder("a");
a.add(new File("x", 10));
Folder b = new Folder("b");
b.add(a).add(new File("y", 5));
Folder c = new Folder("c");
c.add(b).add(a);
System.out.println(c.size());

(a) 15 (b) 25 (c) 10 (d) StackOverflowError

Answer

(b) 25. b = 10 + 5 = 15; c holds b (15) and a again (10) = 25. a is counted twice because it was added in two places. That's not a loop, so there's no stack overflow, but it is why real file systems give each item only one parent.

Interview questions

  1. What is the Composite pattern? A structural pattern that composes objects into tree structures representing part-whole hierarchies, so clients treat single objects and groups uniformly.
  2. Participants? Component, leaf, composite, client.
  3. How does a composite compute a result? It calls the same operation on each child and combines the answers (recursion).
  4. Transparency vs safety? Child-management methods on the component (uniform, but leaves fail at runtime) vs only on the composite (compile-time safety, but clients need the composite type).
  5. Why avoid instanceof in the client? It handles each type and depth by hand, breaks when new types or levels appear, and spreads the logic everywhere.
  6. Risks? Cycles (StackOverflowError), shared children counted twice, deep trees with slow recursive operations, and an overly general component.
  7. Examples? File systems, menus, organisation charts, UI component trees, arithmetic expression trees.
  8. Composite vs Decorator? Decorator wraps one component to add behaviour; Composite holds many to form a whole.
  9. How would you prevent cycles? Reject add(this), keep a parent pointer and refuse to add an ancestor, or allow each item only one parent.
  10. How do you iterate a composite? Recursively (depth-first), or with an explicit stack/queue; the Iterator pattern (episode 40) can hide this.

Glossary

Term Meaning, with an example
Composite pattern Build trees where single objects and groups share one interface. File and Folder both implement Item
Component The shared interface of every node in the tree. Item
Leaf A node with no children. File, Dish
Composite A node that holds children and passes work down to them. Folder, Menu
Tree Data with one root where each item can have children, any number of levels deep
Root The item at the top of a tree. Photos
Children / parent The items directly under a node / the node directly above
Part-whole hierarchy A whole made of parts that may themselves be wholes. A folder of folders
Uniform treatment The client treats one object and a group the same way. one.size() and photos.size()
Recursion A method calling the same method on smaller parts. Folder.size() calls c.size()
Recursive operation An operation done by recursion through the tree. size(), print()
Transparent design Child methods (add) declared on the component for all nodes
Safe design Child methods declared only on the composite
instanceof Checks an object's type. o instanceof File f
Pattern matching for instanceof o instanceof File f both checks and gives a typed variable f
Object The parent class of every class in Java
Default method An interface method with a body. default void add(Item i) { throw ... }
UnsupportedOperationException The exception for "this object can't do that operation"
Exception A problem reported while the program runs
StackOverflowError Thrown when the call stack is full, usually from endless recursion
Call stack The memory Java uses for method calls still waiting to finish
Varargs MenuPart... parts: a method takes any number of arguments
Stream A pipeline over a collection. parts.stream().mapToInt(...).sum()
Method chaining Calling methods one after another because each returns an object. add(a).add(b)
Compile error An error javac reports before the program runs
Megabyte (MB) About a million bytes; 1,000 MB is about a gigabyte (GB)
Indent Spaces in front of a line to show its level

Summary

  • Trees (folders, menus, org charts) can be any depth; code that checks types and handles each level by hand always misses a level.
  • The Composite gives leaves and composites one interface (the component).
  • A composite is a component and has components; operations recurse through the tree.
  • The client gets uniform treatment: no instanceof.
  • Safe (add only on composites, compile-time check) vs transparent (add everywhere, runtime exception). Never let a folder contain itself.

Next episode: The Flyweight pattern.