LOW-LEVEL DESIGN · STRUCTURAL PATTERNS · STRUCTURAL · 29 OF 48

Composite Design Pattern in Java: Trees of Parts and Wholes

The Composite pattern explained with shipping cartons that hold articles and smaller cartons: component, leaf and composite roles, recursive totals with no instanceof checks, safe vs transparent designs, guarding against cycles, sealed interfaces in Java 17, folders, menus and org charts, Composite vs Decorator, and how it appears in Java UI toolkits and LLD interviews.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 17

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 182 lines, with a small main() demo. Save it as ShipmentCompositeDemo.java, then run javac ShipmentCompositeDemo.java && java ShipmentCompositeDemo.

// Composite pattern: cartons hold articles and other cartons; the desk treats them all the same.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ShipmentCompositeDemo {

    public static void main(String[] args) {
        System.out.println("-- Before: the client checks types and walks the tree --");
        NaiveBox naive = new NaiveBox(300);
        naive.contents.add(new NaiveItem(1200));
        System.out.println("naive weight: " + NaiveShipping.weight(naive) + " g");

        System.out.println("-- After: one interface for leaf and group --");
        Carton kit = new Carton("bulb-kit", 100)
                .add(new Article("Bulb", 80, 60))
                .add(new Article("Bulb", 80, 60));
        Carton order = new Carton("order-77", 300)
                .add(new Article("Desk lamp", 1200, 450))
                .add(kit);

        ShippingDesk desk = new ShippingDesk();
        desk.quote(order);                                   // a whole tree
        desk.quote(new Article("Spare bulb", 80, 60));       // a single leaf, same call

        System.out.println("-- Packing list --");
        System.out.print(order.packingList(""));

        System.out.println("-- Cycle guard --");
        try {
            kit.add(order);                                  // order already contains kit
        } catch (IllegalArgumentException e) {
            System.out.println("rejected: " + e.getMessage());
        }
    }
}

// ---------------------------------------------------------------------------
// The problem: every feature repeats the instanceof checks and the tree walk.
// ---------------------------------------------------------------------------
class NaiveItem {
    final int grams;

    NaiveItem(int grams) {
        this.grams = grams;
    }
}

class NaiveBox {
    final int tare;
    final List<Object> contents = new ArrayList<>();

    NaiveBox(int tare) {
        this.tare = tare;
    }
}

final class NaiveShipping {
    private NaiveShipping() {
    }

    static int weight(Object thing) {
        if (thing instanceof NaiveBox box) {
            int sum = box.tare;
            for (Object inside : box.contents) {
                sum += weight(inside);
            }
            return sum;
        }
        if (thing instanceof NaiveItem item) {
            return item.grams;
        }
        throw new IllegalArgumentException("unknown thing"); // a new type breaks this
    }
}

// ---------------------------------------------------------------------------
// Component: what every part of a shipment can answer.
// Sealed (Java 17): the only kinds of part are Article and Carton.
// ---------------------------------------------------------------------------
sealed interface ShipmentPart permits Article, Carton {
    String name();

    int weightGrams();

    int price();

    int articleCount();

    String packingList(String indent);
}

// Leaf: answers from its own fields. This is where recursion stops.
record Article(String name, int weightGrams, int price) implements ShipmentPart {
    @Override
    public int articleCount() {
        return 1;
    }

    @Override
    public String packingList(String indent) {
        return indent + "- " + name + " (" + weightGrams + " g)\n";
    }
}

// Composite: holds children of the component type and combines their answers.
// Safe design: add() exists only here, so adding to an Article will not compile.
final class Carton implements ShipmentPart {
    private final String name;
    private final int tareGrams;
    private final List<ShipmentPart> children = new ArrayList<>();

    Carton(String name, int tareGrams) {
        this.name = name;
        this.tareGrams = tareGrams;
    }

    Carton add(ShipmentPart part) {
        if (part == this || (part instanceof Carton other && other.contains(this))) {
            throw new IllegalArgumentException(part.name() + " would contain " + name);
        }
        children.add(part);
        return this;
    }

    boolean contains(ShipmentPart target) {
        for (ShipmentPart child : children) {
            if (child == target || (child instanceof Carton c && c.contains(target))) {
                return true;
            }
        }
        return false;
    }

    List<ShipmentPart> children() {
        return Collections.unmodifiableList(children);   // never hand out the live list
    }

    @Override
    public String name() {
        return name;
    }

    @Override
    public int weightGrams() {
        int sum = tareGrams;                             // the empty carton weighs something
        for (ShipmentPart child : children) {
            sum += child.weightGrams();                  // leaf or carton: same call
        }
        return sum;
    }

    @Override
    public int price() {
        return children.stream().mapToInt(ShipmentPart::price).sum();
    }

    @Override
    public int articleCount() {
        return children.stream().mapToInt(ShipmentPart::articleCount).sum();
    }

    @Override
    public String packingList(String indent) {
        StringBuilder out = new StringBuilder(indent + "[" + name + "]\n");
        for (ShipmentPart child : children) {
            out.append(child.packingList(indent + "  "));
        }
        return out.toString();
    }
}

// Client: never asks "are you a carton or an article?"
class ShippingDesk {
    void quote(ShipmentPart part) {
        int grams = part.weightGrams();
        int startedKg = (grams + 999) / 1000;
        int fee = 50 + 20 * startedKg;
        System.out.println(part.name() + ": " + part.articleCount() + " article(s), " + grams
                + " g, goods " + part.price() + ", delivery fee " + fee);
    }
}

Notes

The problem

A warehouse needs the total weight of a shipment to quote a delivery fee. The naive client checks the type of each thing. If it is a box, it adds the box's own weight and loops over the contents. If it is an item, it returns the grams. Now repeat that walk for price, for item count and for the packing list. Every feature copies the type checks, and a new kind of container breaks all of them.

NaiveShipping.weight
int weight(Object thing) {
  if (thing instanceof NaiveBox b) {
    int sum = b.tare;
    for (Object o : b.contents)
      sum += weight(o);
    return sum;
  }
  if (thing instanceof NaiveItem i)
    return i.grams;
  throw new IllegalArgumentException();
}

The idea

The idea: give single items and groups the same interface. A group holds children of that same interface, and answers any question by asking its children and combining their answers. More formally, composite arranges objects into tree structures that represent part and whole hierarchies, and lets clients treat individual objects and compositions of objects uniformly. The client never needs to ask which one are you.

Composite in one line
  • give single items and groups
  • the SAME interface
  • a group holds children of
  • that interface and answers
  • by asking its children
  • the client never asks
  • "which one are you?"

The roles

Four roles with our names. The component is the shipment part interface, the type everyone talks to. The leaf is an article, a real product with a weight and a price and no children. The composite is a carton, which has its own empty weight and a list of shipment parts inside. Notice the link going back up: a carton contains components, so it can contain articles or other cartons. The shipping desk is the client.

Component and leaf

The component interface lists what every part can answer: a name, a weight in grams, a price and how many articles it holds. The leaf is a Java record. Its name, weight and price come straight from its fields, and its article count is simply one. The leaf is where the recursion stops, so leaf methods are always short and never loop.

ShipmentPart and Article
interface ShipmentPart {
    String name();
    int weightGrams();
    int price();
    int articleCount();
}

record Article(String name,
        int weightGrams, int price)
        implements ShipmentPart {
    public int articleCount() { return 1; }

The composite

The carton keeps its own empty weight, called tare, and a list of children typed as the interface. Its weight is the tare plus the weight of each child. Its price is the sum of the children's prices, because an empty carton is free. Each child might be an article or another carton, and the carton does not care. If it is a carton, that call simply repeats the same logic one level down.

Carton
class Carton implements ShipmentPart {
    private final int tareGrams;
    private final List<ShipmentPart> kids;

    public int weightGrams() {
        int sum = tareGrams;
        for (ShipmentPart p : kids)
            sum += p.weightGrams();
        return sum;
    }
}

A real tree

Here is one real shipment, order seventy seven. An outer carton weighing three hundred grams holds a desk lamp of twelve hundred grams and a small bulb kit carton. The bulb kit weighs one hundred grams empty and holds two bulbs of eighty grams each. Notice that the bulb kit is itself a carton, built with the same add method. The tree can be as deep as the warehouse needs.

Building it
Carton kit = new Carton("bulb-kit", 100)
    .add(new Article("Bulb", 80, 60))
    .add(new Article("Bulb", 80, 60));
Carton order = new Carton("order-77", 300)
    .add(new Article("Desk lamp",
                     1200, 450))
    .add(kit);

One call

The desk asks the outer carton for its weight, exactly as it would ask a single article. The outer carton starts with three hundred and asks the lamp, which says twelve hundred. It asks the bulb kit, which starts with one hundred and asks both bulbs for eighty each, returning two hundred and sixty. The outer carton returns one thousand seven hundred and sixty grams, and the desk quotes a fee of ninety.

Safe vs transparent

Where should add and remove live? In the transparent design, they sit on the component interface, so the client treats everything identically, but an article must then throw an unsupported operation exception at runtime. In the safe design, which we use, only the carton has add and remove, so the compiler stops you adding to an article, but code that builds trees must know it holds a carton. Reading code stays uniform either way.

Two designs
  • transparent: add/remove on
  • the component interface
  • + client never casts
  • - Article.add() must throw
  • UnsupportedOperationException
  • safe: add/remove only on
  • the composite (our choice)
  • + the compiler stops misuse
  • - code that builds trees
  • must know it has a Carton

Practical details

A few practical details. Guard against cycles: our add method refuses a carton that would end up inside itself, even several levels down, or every total would recurse forever. Parent links are optional but help with full paths and moving nodes. Very large trees can cache totals and clear the cache when something changes. In Java seventeen, a sealed interface can list the only two kinds of part, which makes the tree's shape explicit.

Get these right
  • cycles: a carton must not
  • contain itself, even deep
  • down: check in add()
  • parent links: optional, help
  • with paths and moving nodes
  • caching: big trees may cache
  • totals, clear on change
  • deep trees: recursion depth
  • may need an explicit stack
  • Java 17: sealed interface

When to use it

Use composite when your data is genuinely a tree of parts and wholes, when clients should not care whether they hold one thing or many, and when operations naturally combine children: sum, maximum, render, or search. Avoid it for a flat list, where a plain collection is simpler. Also avoid it when leaves and groups share almost no operations. Forcing them behind one interface then creates many methods that make no sense on one side.

Use / avoid
  • use when:
  • • data is a part-whole tree
  • • clients should not care if
  • they hold one or many
  • • operations combine children
  • (sum, max, render, search)
  • avoid when:
  • • the structure is flat
  • • leaves and groups need very
  • different operations

Everyday trees

Once you see it, composite is everywhere. A file system has files and folders, and a folder's size is the sum of its contents. A restaurant menu has dishes and sections with sub sections. An org chart has employees and departments, and the salary of a department rolls up. Product bundles can contain other bundles. User interfaces nest buttons inside panels, and maths expressions combine numbers into bigger expressions.

Composite everywhere
  • file system: File + Folder
  • restaurant menu: Dish +
  • Section with sub-sections
  • org chart: Employee +
  • Department, total salary
  • product bundles: price of a
  • bundle of bundles
  • UI: Button + Panel
  • maths: Number + Expression

In Java

Java's user interface toolkits are built on composite. In AWT, the container class extends component and holds a list of components, so a panel can hold buttons and other panels. Swing builds on the same classes. In JavaFX, parent extends node, and groups and panes hold child nodes. When a window lays itself out or paints, it walks the tree in exactly the recursive way we just saw.

In Java
java.awt.Container extends Component
  // a Container holds Components,
  // and is one itself
Swing: JPanel inside JPanel
JavaFX: Parent extends Node,
  Group and Pane hold children

layout and paint walk the tree

Neighbours

Composite and decorator look alike, because both are recursive: an object holds something of its own type. A decorator wraps exactly one object and adds behaviour to it. A composite holds many children and combines their answers. Composite also pairs well with other patterns. An iterator can walk the tree in depth first order, and a visitor adds new operations, like customs forms, without editing every node class.

Composite compared
  • Decorator: also recursive,
  • but ONE wrapped child and
  • it ADDS behaviour
  • Composite: MANY children and
  • it COMBINES their answers
  • works well with:
  • Iterator: walk the tree
  • Visitor: new operations
  • without editing nodes

In LLD interviews

In interviews, design an in memory file system is the classic composite question: total size, find by name, and list a folder recursively. Food app menus, company hierarchies and expression evaluators use it too. Common mistakes: type checks left in the client, leaves carrying an empty children list for no reason, no cycle check, and returning the internal list so callers can change the tree behind the composite's back.

Where it shows up
  • design a file system:
  • size, find, ls -R
  • restaurant or food app menu
  • company hierarchy, approvals
  • expression evaluator
  • mistakes:
  • • instanceof checks in client
  • • leaf with an empty list
  • • no cycle check
  • • returning the live list

Say it like this

How to say it, for a file system. Entry is the component interface, file is the leaf, and folder is the composite that holds a list of entries. Size on a folder sums its children, so callers never check types. I put add only on folder, the safe design, so the compiler prevents adding to a file, and add refuses a folder that would contain itself.

In the interview
  • "Entry is the component; File
  • is the leaf, Folder is the
  • composite holding a list of
  • Entry. size() on a folder
  • sums its children, so callers
  • never check types. add() is
  • only on Folder, the safe
  • design, with a cycle check."

Interview questions

What is the Composite pattern?

A structural pattern that arranges objects into a tree of parts and wholes. Leaves and containers share one component interface, and a container implements each operation by delegating to its children and combining their results, so clients treat one object and a group the same way.

What is the difference between the safe and transparent Composite designs?

Transparent puts child management methods like add and remove on the component interface, so clients never cast but leaves must throw at runtime. Safe puts them only on the composite, so misuse is a compile error but tree-building code must know it holds a composite.

How do you prevent cycles in a Composite?

When adding a child, reject it if it is the container itself or if the child (recursively) already contains the container. Without this check, operations like size or weight recurse forever and end in a StackOverflowError.

How is Composite different from Decorator?

Both use recursive composition. A decorator wraps exactly one object of the same interface and adds behaviour. A composite holds any number of children and combines their answers, for example by summing sizes.

Where is Composite used in the Java standard library?

In the UI toolkits: java.awt.Container extends Component and holds child Components, which Swing builds on, and in JavaFX Parent extends Node and holds child nodes. Layout and painting walk the tree recursively.

How would you design an in-memory file system with Composite?

Define an Entry component with name and size. File is a leaf with its own size; Folder is a composite holding a map or list of entries, and its size sums its children. Add path lookup, a cycle check, and return unmodifiable views of children.

When should you avoid Composite?

When the data is flat, a simple list is enough. Also when leaves and containers share very few operations, because forcing them behind one interface creates methods that are meaningless on one side.

How do you add new operations to a Composite without editing every class?

Use the Visitor pattern: each node accepts a visitor, and each new operation is one visitor class. With a sealed interface in Java 17, a switch with pattern matching over the permitted types is a lighter alternative.