Composite Design Pattern in Java
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
| Component | Responsibility | In the Basic Example |
|---|---|---|
| Component | Interface shared by every node in the tree | CatalogItem |
| Leaf | A node with no children; does the real work | Product |
| Composite | Stores children and implements operations by delegating to them | Bundle |
| Client | Works with any node through the component interface | The 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.
Bundle is a CatalogItem and also contains CatalogItems, so bundles can hold products or other bundles.CatalogItemis the component; the client depends only on it.Product(leaf) andBundle(composite) both implement it.Bundleaggregates zero or moreCatalogItems (hollow diamond). Because the child type is the interface, a bundle can contain products or other bundles.- Only the composite has
add(). Leaves cannot hold children, which is the "safe" variant of the pattern.
5. Step-by-Step Execution Flow
- The client builds the tree: an accessory pack bundle, then a festive combo bundle that contains a phone, the accessory pack and earbuds.
- It calls
price()on the festive combo. - The combo calls
price()on each child. The phone and earbuds (leaves) return their own prices. - The accessory pack is a composite, so it calls its own children, adds 499 and 299, applies 10% off and returns 718.20.
- The combo adds 24,999 + 718.20 + 1,999, applies 5% off and returns 26,330.39.
- 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,
ContainerextendsComponentand 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:
CompositePropertySourcecombines property sources,CompositeCacheManagercombines cache managers, and Actuator'sCompositeHealthContributorgroups health indicators. Micrometer'sCompositeMeterRegistryforwards metrics to several registries.
7. Problem Without the Pattern
A cart that handles products and bundles as unrelated types:
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.");
}
}
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
instanceofchain. - No nesting:
Bundleaccepts 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.
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
Productis a record that implementsCatalogItem; itsname()andprice()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
+ 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
- The accessory pack totals 798.00, less 10%: 718.20.
- The festive combo totals 27,716.20, less 5%: 26,330.39.
- The cart adds the combo and the gift card through the same
price()call.
Practical Example: Loan Eligibility Rules
Problem: a bank's personal-loan policy combines simple checks with AND and OR, and risk teams change the combination often. Rejected applicants must be told which checks failed.
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class LoanEligibilityDemo {
record Applicant(String name, int age, int creditScore, boolean kycVerified, String country, long monthlyIncome) { }
// Component: every rule, simple or combined, has the same interface
sealed interface Rule permits MinAge, MinCreditScore, KycVerified, CountryIn, MinIncome, AllOf, AnyOf {
boolean test(Applicant applicant);
String describe();
}
// Leaves
record MinAge(int years) implements Rule {
public boolean test(Applicant a) { return a.age() >= years; }
public String describe() { return "age >= " + years; }
}
record MinCreditScore(int score) implements Rule {
public boolean test(Applicant a) { return a.creditScore() >= score; }
public String describe() { return "credit score >= " + score; }
}
record KycVerified() implements Rule {
public boolean test(Applicant a) { return a.kycVerified(); }
public String describe() { return "KYC verified"; }
}
record CountryIn(Set<String> countries) implements Rule {
public boolean test(Applicant a) { return countries.contains(a.country()); }
public String describe() { return "country in " + countries.stream().sorted().toList(); }
}
record MinIncome(long rupees) implements Rule {
public boolean test(Applicant a) { return a.monthlyIncome() >= rupees; }
public String describe() { return "monthly income >= " + rupees; }
}
// Composites: combine any rules, including other composites
record AllOf(List<Rule> rules) implements Rule {
AllOf(Rule... rules) { this(List.of(rules)); }
public boolean test(Applicant a) { return rules.stream().allMatch(r -> r.test(a)); }
public String describe() { return rules.stream().map(Rule::describe).collect(Collectors.joining(" AND ", "(", ")")); }
}
record AnyOf(List<Rule> rules) implements Rule {
AnyOf(Rule... rules) { this(List.of(rules)); }
public boolean test(Applicant a) { return rules.stream().anyMatch(r -> r.test(a)); }
public String describe() { return rules.stream().map(Rule::describe).collect(Collectors.joining(" OR ", "(", ")")); }
}
// Lists the leaf rules an applicant failed, walking the tree recursively
static List<String> failures(Rule rule, Applicant a) {
return switch (rule) {
case AllOf all -> all.rules().stream().flatMap(r -> failures(r, a).stream()).toList();
case AnyOf any -> any.test(a) ? List.of() : List.of("none of " + any.describe());
default -> rule.test(a) ? List.of() : List.of(rule.describe());
};
}
public static void main(String[] args) {
Rule personalLoan = new AllOf(
new MinAge(21),
new KycVerified(),
new CountryIn(Set.of("IN")),
new AnyOf(new MinCreditScore(750), new AllOf(new MinCreditScore(650), new MinIncome(80_000))));
System.out.println("Policy: " + personalLoan.describe());
List<Applicant> applicants = List.of(
new Applicant("Asha", 29, 780, true, "IN", 60_000),
new Applicant("Ravi", 34, 690, true, "IN", 95_000),
new Applicant("Kabir", 19, 640, false, "IN", 30_000));
for (Applicant a : applicants) {
boolean approved = personalLoan.test(a);
System.out.println(a.name() + ": " + (approved ? "APPROVED" : "REJECTED " + failures(personalLoan, a)));
}
}
}
Important classes and methods
Ruleis a sealed component interface: five leaf rules and two composites (AllOf,AnyOf).- All nodes are records, so the whole rule tree is immutable and safe to share between request threads.
failures()uses Java 21 pattern matching forswitchto walk the tree and collect the leaf rules that failed.
Expected output
Policy: (age >= 21 AND KYC verified AND country in [IN] AND (credit score >= 750 OR (credit score >= 650 AND monthly income >= 80000)))
Asha: APPROVED
Ravi: APPROVED
Kabir: REJECTED [age >= 21, KYC verified, none of (credit score >= 750 OR (credit score >= 650 AND monthly income >= 80000))]
How it runs
describe()on the root prints the entire policy by recursing through every node.- Asha passes through the 750 credit-score branch; Ravi through the "650 plus 80,000 income" branch.
- Kabir fails three parts, and the report names each one.
Real-World Enterprise Example: Grouped Health Checks
Problem: an order service reports its health to Kubernetes and a dashboard. Dependencies are grouped, checks must run in parallel, a slow dependency must not hang the whole report, and the overall status is the worst status found.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class HealthCheckDemo {
enum Status { UP, DEGRADED, DOWN } // ordered from best to worst
record Result(String name, Status status, String detail, List<Result> children) {
void print(String indent) {
System.out.println(indent + name + ": " + status + (detail.isEmpty() ? "" : " (" + detail + ")"));
children.forEach(child -> child.print(indent + " "));
}
}
// Component
interface HealthCheck {
String name();
Result check(ExecutorService executor);
}
// Leaf: one dependency, simulated with a delay and a fixed outcome
record DependencyCheck(String name, long latencyMillis, Status outcome, String detail) implements HealthCheck {
public Result check(ExecutorService executor) {
try {
Thread.sleep(latencyMillis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return new Result(name, outcome, detail, List.of());
}
}
// Composite: runs children in parallel, with a timeout, and reports the worst status
record HealthGroup(String name, List<HealthCheck> children, long timeoutMillis) implements HealthCheck {
public Result check(ExecutorService executor) {
List<CompletableFuture<Result>> futures = new ArrayList<>();
for (HealthCheck child : children) {
futures.add(CompletableFuture.supplyAsync(() -> child.check(executor), executor)
.completeOnTimeout(new Result(child.name(), Status.DOWN, "timed out", List.of()), timeoutMillis, TimeUnit.MILLISECONDS));
}
List<Result> results = futures.stream().map(CompletableFuture::join).toList(); // keeps child order
Status worst = results.stream().map(Result::status).max(Enum::compareTo).orElse(Status.UP);
return new Result(name, worst, "", results);
}
}
public static void main(String[] args) {
HealthCheck application = new HealthGroup("order-service", List.of(
new HealthGroup("infrastructure", List.of(
new DependencyCheck("postgres", 40, Status.UP, "pool 7/20 in use"),
new DependencyCheck("redis", 20, Status.UP, ""),
new DependencyCheck("disk", 5, Status.DEGRADED, "12% free")), 500),
new HealthGroup("external", List.of(
new DependencyCheck("payment-gateway", 60, Status.UP, ""),
new DependencyCheck("sms-provider", 3_000, Status.UP, "")), 300)), // too slow: will time out
1_000);
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
long start = System.nanoTime();
Result result = application.check(executor);
long millis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
result.print("");
System.out.println("Finished within the 1 second budget: " + (millis < 1_000));
}
}
}
Important classes and methods
HealthCheckis the component.DependencyCheckis a leaf, andHealthGroupis a composite that can contain checks or other groups.HealthGroup.check()starts every child on a virtual thread and usescompleteOnTimeout()to mark slow children asDOWN.- The
Statusenum is ordered from best to worst, somax()picks the worst child status. - Results form a tree too, so
print()mirrors the check structure.
Expected output
order-service: DOWN
infrastructure: DEGRADED
postgres: UP (pool 7/20 in use)
redis: UP
disk: DEGRADED (12% free)
external: DOWN
payment-gateway: UP
sms-provider: DOWN (timed out)
Finished within the 1 second budget: true
How it runs
- Both groups run at the same time, and each runs its own children in parallel.
- Disk space is low, so the infrastructure group is
DEGRADED. - The SMS provider takes 3 seconds, but its group's timeout is 300 ms, so it is reported as
DOWNand the report still finishes within one second. - The worst child status propagates upward: the service is
DOWN.
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
CopyOnWriteArrayListfor 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
| Aspect | Composite | Decorator | Iterator | Visitor |
|---|---|---|---|---|
| Intent | Treat a tree like a single object | Add behaviour to one object | Traverse a collection | Add operations to a structure without changing its classes |
| Children | Many | Exactly one | Not applicable | Not applicable |
| Recursion | Down the tree, results combined | Through a chain of wrappers | Hidden inside the iterator | Double dispatch per node |
| Typical pairing | The structure | Wraps nodes | Walks the composite | Operates 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.