00:00

Composite Design Pattern in Java

Last updated:

The composite design pattern in Java lets you build tree structures in which single objects and groups of objects share one interface, so client code treats them the same way. A product and a bundle of products both answer price(); the bundle simply asks its children and combines their answers.

It matters because hierarchies are everywhere: bundles inside bundles, rules made of rules, health checks grouped under other health checks. Without a common interface, every piece of client code needs instanceof checks and its own recursion, and each new node type breaks that code. Composite is a structural design pattern that turns those trees into objects you can use as a single unit.

1. What Is the Composite Design Pattern?

The GoF intent is: "Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly."

The pattern has two kinds of node behind one component interface. A leaf does the work itself: a product knows its price. A composite holds a list of components and implements each operation by delegating to its children and combining their results: a bundle adds up its children's prices and applies its discount.

Because a composite's children are typed as the component interface, a child can be a leaf or another composite. That one decision gives you trees of any depth with no extra code. Operations travel down the tree through ordinary method calls, and results bubble back up.

Composite relies on polymorphism to remove type checks from clients, and follows the Open/Closed Principle: a new node type is a new class, and no client changes.

2. Key Components

ComponentResponsibilityIn the Basic Example
ComponentInterface shared by every node in the treeCatalogItem
LeafA node with no children; does the real workProduct
CompositeStores children and implements operations by delegating to themBundle
ClientWorks with any node through the component interfaceThe cart in main

The client calls an operation on the root. Leaves answer directly; composites call it on each child and combine the answers.

3. When Is Composite Useful?

  • Nested product bundles: a festive combo that contains a phone, earbuds and an accessory pack, which itself contains items.
  • Business rules: loan eligibility built from simple checks combined with AND and OR, nested to any depth.
  • System status: an application's health made of groups of dependency checks.

4. UML Class Diagram

The diagram shows the Basic Example.

Composite UML class diagram The Client uses the CatalogItem interface. Product and Bundle implement CatalogItem. Bundle holds zero or more CatalogItem children. Client uses «interface» CatalogItem + name(): String + price(): BigDecimal + print(indent): void implements leaf Product - name: String - price: BigDecimal composite Bundle - children: List<CatalogItem> - discountPercent: int + add(item): Bundle children 0..*
Composite: Bundle is a CatalogItem and also contains CatalogItems, so bundles can hold products or other bundles.
  1. CatalogItem is the component; the client depends only on it.
  2. Product (leaf) and Bundle (composite) both implement it.
  3. Bundle aggregates zero or more CatalogItems (hollow diamond). Because the child type is the interface, a bundle can contain products or other bundles.
  4. Only the composite has add(). Leaves cannot hold children, which is the "safe" variant of the pattern.

5. Step-by-Step Execution Flow

  1. The client builds the tree: an accessory pack bundle, then a festive combo bundle that contains a phone, the accessory pack and earbuds.
  2. It calls price() on the festive combo.
  3. The combo calls price() on each child. The phone and earbuds (leaves) return their own prices.
  4. The accessory pack is a composite, so it calls its own children, adds 499 and 299, applies 10% off and returns 718.20.
  5. The combo adds 24,999 + 718.20 + 1,999, applies 5% off and returns 26,330.39.
  6. The client gets one number, whatever the tree's depth.

6. Real-World Use Cases

  • E-commerce: bundles, kits and category trees whose totals or stock levels roll up.
  • Payments and banking: eligibility and fraud rules combined with AND/OR, and account hierarchies (a group account made of sub-accounts) with rolled-up balances.
  • Notifications: a recipient group that contains users and other groups, sending to everyone with one call.
  • The JDK: in AWT, Container extends Component and holds other components, so a panel is laid out and painted like a single widget. Swing builds on the same structure.
  • Spring and Spring Boot: CompositePropertySource combines property sources, CompositeCacheManager combines cache managers, and Actuator's CompositeHealthContributor groups health indicators. Micrometer's CompositeMeterRegistry forwards metrics to several registries.

7. Problem Without the Pattern

A cart that handles products and bundles as unrelated types:

CartWithoutComposite.java
import java.math.BigDecimal;
import java.util.List;

public class CartWithoutComposite {

    record Product(String name, BigDecimal price) { }

    record Bundle(String name, int discountPercent, List<Product> products) { }   // bundles can only hold products

    // The client must know about every kind of item and treat each one differently
    static BigDecimal cartTotal(List<Object> cart) {
        BigDecimal total = BigDecimal.ZERO;
        for (Object item : cart) {
            if (item instanceof Product p) {
                total = total.add(p.price());
            } else if (item instanceof Bundle b) {
                BigDecimal sum = BigDecimal.ZERO;
                for (Product p : b.products()) {
                    sum = sum.add(p.price());
                }
                total = total.add(sum.multiply(BigDecimal.valueOf(100 - b.discountPercent())).movePointLeft(2));
            } else {
                throw new IllegalArgumentException("Unknown cart item: " + item);   // every new type breaks here
            }
        }
        return total;
    }

    public static void main(String[] args) {
        Bundle starterKit = new Bundle("Starter kit", 10, List.of(
                new Product("Phone case", new BigDecimal("499.00")),
                new Product("Screen guard", new BigDecimal("299.00"))));
        List<Object> cart = List.of(new Product("Phone", new BigDecimal("24999.00")), starterKit);

        System.out.println("Cart total: Rs. " + cartTotal(cart));
        System.out.println("A bundle inside a bundle? Not possible: Bundle only accepts Product.");
    }
}
Console
Cart total: Rs. 25717.2000
A bundle inside a bundle? Not possible: Bundle only accepts Product.
  • Type checks everywhere: the cart, invoices and stock reports each need the same instanceof chain.
  • No nesting: Bundle accepts only products, so a bundle of bundles is impossible.
  • Duplicated logic: the discount calculation lives in the client, and the stray four decimal places in the total show how easily copies drift.
  • Fragile: any new item type, such as a gift card, breaks every client.

8. Solution Using the Pattern

Give products and bundles one CatalogItem interface, let Bundle hold a list of CatalogItem, and move the discount logic into Bundle.price().

The cart now adds up item.price() with no type checks. Bundles nest to any depth. The pricing rule lives in one class and rounds consistently. A gift card is just another leaf, and no existing code changes.

9. Composite Design Pattern in Java: Code Examples

Each example is a single file that runs on Java 21 with java FileName.java.

Basic Example: Nested Product Bundles

Problem: fix section 7 so that bundles can contain products and other bundles, and the cart treats all items the same.

ProductBundleDemo.java
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

public class ProductBundleDemo {

    // Component: what the client sees for every item
    interface CatalogItem {
        String name();
        BigDecimal price();
        void print(String indent);
    }

    // Leaf
    record Product(String name, BigDecimal price) implements CatalogItem {
        Product(String name, String price) { this(name, new BigDecimal(price)); }

        public void print(String indent) {
            System.out.println(indent + "- " + name + "  Rs. " + price);
        }
    }

    // Composite: holds children of the same component type, so bundles can nest
    static final class Bundle implements CatalogItem {
        private final String name;
        private final int discountPercent;
        private final List<CatalogItem> children = new ArrayList<>();

        Bundle(String name, int discountPercent) {
            this.name = name;
            this.discountPercent = discountPercent;
        }

        Bundle add(CatalogItem item) {
            children.add(item);
            return this;
        }

        public String name() { return name; }

        public BigDecimal price() {
            BigDecimal sum = children.stream().map(CatalogItem::price).reduce(BigDecimal.ZERO, BigDecimal::add);   // recursion
            return sum.multiply(BigDecimal.valueOf(100 - discountPercent))
                      .divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
        }

        public void print(String indent) {
            System.out.println(indent + "+ " + name + " (" + discountPercent + "% off)  Rs. " + price());
            children.forEach(child -> child.print(indent + "    "));
        }
    }

    public static void main(String[] args) {
        Bundle accessories = new Bundle("Accessory pack", 10)
                .add(new Product("Phone case", "499.00"))
                .add(new Product("Screen guard", "299.00"));

        Bundle festiveCombo = new Bundle("Festive combo", 5)
                .add(new Product("Phone", "24999.00"))
                .add(accessories)                                  // a bundle inside a bundle
                .add(new Product("Earbuds", "1999.00"));

        List<CatalogItem> cart = List.of(festiveCombo, new Product("Gift card", "500.00"));

        cart.forEach(item -> item.print(""));
        BigDecimal total = cart.stream().map(CatalogItem::price).reduce(BigDecimal.ZERO, BigDecimal::add);
        System.out.println("Cart total: Rs. " + total);
    }
}

Important classes and methods

  • Product is a record that implements CatalogItem; its name() and price() come from the record components.
  • Bundle.price() sums its children's prices recursively, then applies its own discount.
  • print() walks the same tree, adding indentation per level.

Expected output

Console
+ Festive combo (5% off)  Rs. 26330.39
    - Phone  Rs. 24999.00
    + Accessory pack (10% off)  Rs. 718.20
        - Phone case  Rs. 499.00
        - Screen guard  Rs. 299.00
    - Earbuds  Rs. 1999.00
- Gift card  Rs. 500.00
Cart total: Rs. 26830.39

How it runs

  1. The accessory pack totals 798.00, less 10%: 718.20.
  2. The festive combo totals 27,716.20, less 5%: 26,330.39.
  3. The cart adds the combo and the gift card through the same price() call.

10. Best Practices and Common Mistakes

Best practices

  • Keep the component interface focused on operations that make sense for both leaves and composites.
  • Put child-management methods (add, remove) on the composite unless clients truly need to treat them uniformly.
  • Prefer immutable trees (records, List.copyOf) when the structure is built once and read often.
  • Thread safety: immutable trees can be shared freely. If a tree changes while others read it, use CopyOnWriteArrayList for read-heavy children or guard changes with a lock.

Common mistakes

  • Cycles: adding a bundle to itself, directly or indirectly, causes infinite recursion.
  • Leaky leaves: leaves that throw on add() because the method was forced onto the shared interface.
  • Recomputing deep trees on every call when the result rarely changes.
  • Overengineering: using Composite for a flat list that will never nest.

11. When to Use and When Not to Use

Use it when the domain really is a part-whole hierarchy of unknown depth, and clients should not care whether they hold one item or a group.

Avoid it when leaves and groups need very different operations, which would make the shared interface artificial, when the structure is always exactly one level deep, or when strict type rules apply, such as "a bundle may contain only physical products", that a uniform interface cannot express without runtime checks.

12. Advantages and Disadvantages

Advantages

  • Uniform client code with no type checks.
  • Unlimited nesting for free.
  • Open/Closed: new node types do not change clients.
  • Natural recursion for totals, validation and rendering.

Disadvantages

  • Overly general design: hard to restrict which children are allowed.
  • Deep trees can be slow or, in extreme cases, overflow the stack.
  • Debugging long chains of recursive calls is harder.

13. Comparison with Similar Patterns

AspectCompositeDecoratorIteratorVisitor
IntentTreat a tree like a single objectAdd behaviour to one objectTraverse a collectionAdd operations to a structure without changing its classes
ChildrenManyExactly oneNot applicableNot applicable
RecursionDown the tree, results combinedThrough a chain of wrappersHidden inside the iteratorDouble dispatch per node
Typical pairingThe structureWraps nodesWalks the compositeOperates on the composite

Choose Composite to model the hierarchy, a Decorator to add behaviour to one node, an Iterator to give clients a flat walk over the tree, and a Visitor when you need many unrelated operations on a stable tree. With sealed interfaces and pattern matching in Java 21, a switch over node types often replaces a classic Visitor, as the failures() method shows.

14. Summary

  • The composite design pattern in Java treats single objects and groups of objects through one interface.
  • Purpose: model part-whole hierarchies and remove type checks from clients.
  • Components: Component, Leaf, Composite, Client.
  • Composites delegate each operation to their children and combine the results, recursively.
  • Used for bundles, rule engines, health checks, UI containers and Spring's composite managers.
  • Benefits: uniform code, unlimited nesting and easy extension.
  • Guard against cycles, prefer immutable trees for thread safety, and skip the pattern for flat data.

15. Java Design Pattern Interview Questions and Answers

Q1. Should add() and remove() be declared on the component interface or only on the composite?

This is the GoF trade-off between transparency and safety. On the component, clients treat every node identically, but leaves must reject the calls at runtime. On the composite only, misuse becomes a compile error, but clients must know when they hold a composite. Most modern Java code chooses safety, and sealed interfaces make the "which kind is this?" check exhaustive.

Q2. How do you stop a bundle from being added inside itself?

Before adding, check that the new child does not already contain the parent anywhere in its subtree. For large trees, keep a parent reference in each node and walk up the ancestors instead.

Bundle add(CatalogItem item) {
    if (item == this || (item instanceof Bundle b && b.contains(this))) {
        throw new IllegalArgumentException("Cycle: " + item.name());
    }
    children.add(item);
    return this;
}

boolean contains(CatalogItem target) {
    return children.stream().anyMatch(c -> c == target || (c instanceof Bundle b && b.contains(target)));
}
Q3. A category tree has 50,000 nodes and price() is called on every page view. How do you speed it up?

Cache each composite's computed value and invalidate it, and its ancestors' caches, only when a child changes. If the tree is immutable, compute values once at build time. For read-heavy catalogues, precompute aggregates in the database or a search index instead of recursing at request time.

Q4. How do you store a composite tree in a relational database?

The simplest model is an adjacency list: each row has a parent_id, which in JPA maps to a @ManyToOne parent and a @OneToMany children collection. Load a whole subtree with a recursive common table expression (WITH RECURSIVE), supported by PostgreSQL, MySQL 8 and others. For very read-heavy trees, a closure table or materialised path makes subtree queries cheaper.

Q5. One thread iterates a composite while another adds a child. What happens, and how do you prevent it?

With an ArrayList, the iterating thread can get a ConcurrentModificationException or see inconsistent data, because ArrayList is not thread-safe. Options are immutable trees replaced as a whole, CopyOnWriteArrayList for rarely changed children, or a read-write lock around structural changes.