Simple definition#
The Composite pattern arranges objects in a tree and gives single objects (leaves) and groups (composites) the same interface. Client code can then call price() on a single product or on a bundle of bundles without caring which it has.
GoF intent: “Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.”
The problem#
An online shop sells products and bundles. A bundle contains products and other bundles, and applies its own discount. A cart can hold both.
Without Composite, every piece of code that computes a price, counts items or prints the cart needs if (item instanceof Bundle) { loop over children... recursively }. That recursion and type-checking is duplicated in every operation, and adding a new kind of item touches all of them.
Real-world analogy#
A company organisation chart. You can ask any unit, from a single employee to the whole division, “what is your salary cost?” An employee answers directly; a department asks each of its members and sub-departments and adds up the answers.
Structure#
- Component (
CatalogItem) — the common interface. - Leaf (
Product) — has no children; does the work itself. - Composite (
Bundle) — stores children and implements operations by delegating to them. - Client — works only with
CatalogItem.
classDiagram
direction TB
class CatalogItem {
<<sealed interface>>
+name() String
+price() BigDecimal
+itemCount() int
+print(String)
}
class Product {
<<record>>
name
price
}
class Bundle {
-int discountPercent
-List~CatalogItem~ children
+add(CatalogItem) Bundle
}
CatalogItem <|.. Product
CatalogItem <|.. Bundle
Bundle o--> "0..*" CatalogItem : childrenThe recursive arrow from Bundle back to CatalogItem is the heart of the pattern: a composite contains components, which may themselves be composites.
Java implementation#
The code is in examples/java/src/hub/patterns/composite/CompositeDemo.java.
/** Component: the one interface that clients use for single products and bundles alike. */
sealed interface CatalogItem permits Product, Bundle {
String name();
BigDecimal price();
int itemCount();
void print(String indent);
}/** Leaf: has no children. */
record Product(String name, BigDecimal price) implements CatalogItem {
@Override public int itemCount() { return 1; }
@Override public void print(String indent) {
System.out.printf("%s- %s %s%n", indent, name, price);
}
}/** Composite: holds children (products or other bundles) and delegates to them. */
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;
}
@Override public String name() { return name; }
@Override public BigDecimal price() {
BigDecimal sum = children.stream().map(CatalogItem::price).reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal factor = BigDecimal.valueOf(100 - discountPercent).movePointLeft(2);
return sum.multiply(factor).setScale(2, RoundingMode.HALF_EVEN);
}
@Override public int itemCount() {
return children.stream().mapToInt(CatalogItem::itemCount).sum();
}
@Override public void print(String indent) {
System.out.printf("%s+ %s (-%d%%) %s%n", indent, name, discountPercent, price());
children.forEach(child -> child.print(indent + " "));
}
}+ Home office bundle (-5%) 1527.60
- Laptop 1200.00
- Monitor 300.00
+ Peripherals kit (-10%) 108.00
- Mouse 40.00
- Keyboard 80.00
Cart: 5 items, total 1537.59The cart total adds a three-level bundle and a single cable with one expression: cart.stream().map(CatalogItem::price). The peripherals kit is discounted 10% inside the office bundle, which is then discounted another 5%.
Step-by-step walkthrough#
- Define the component interface with operations that make sense for both leaves and groups: price, item count, printing.
- Leaves implement them directly. A
Productreturns its own price. - Composites implement them by delegating to children and combining the results (sum, then discount).
- Recursion is implicit.
Bundle.price()callschild.price(); if the child is a bundle, it recurses. No caller writes a loop over levels. - Sealed interface.
sealed ... permits Product, Bundledocuments the closed set of node types and letsswitchexpressions overCatalogItembe checked for exhaustiveness.
Transparency versus safety#
Where do child-management methods (add, remove) go?
| Design | add() declared on | Benefit | Cost |
|---|---|---|---|
| Transparency (GoF default) | The component interface | Clients treat everything uniformly | Leaves must reject add() at runtime |
| Safety (this example) | Only the composite | The compiler prevents adding to a leaf | Clients must know they hold a composite to add children |
Modern Java code usually prefers safety: build trees with the concrete composite type, then pass them around as the component type.
Advantages and disadvantages#
| Advantages | Disadvantages |
|---|---|
| Uniform treatment of single objects and groups simplifies clients | The component interface can become too general for some leaves |
| New leaf or composite types fit without client changes | Hard to restrict which children a composite may contain (type rules move to runtime checks) |
| Natural fit for recursive data: files, UI trees, ASTs, org charts | Deep trees can be expensive to traverse repeatedly; consider caching aggregate values |
When to use it#
- Your data is a part-whole hierarchy (a tree) and clients should not care about the difference.
- Operations naturally aggregate over children: totals, rendering, validation, permissions.
When not to use it#
- The structure is flat, or leaves and groups behave very differently.
- You need many unrelated operations over the tree: consider pairing Composite with Visitor, or a sealed hierarchy with pattern matching.
Common mistakes#
- Type checks in clients (
instanceof Bundle) defeat the purpose. - Exposing the mutable children list, letting callers bypass the composite’s rules.
- Parent pointers out of sync when children move, if you maintain them.
Real-world uses#
- Files and directories:
java.nio.file.Pathtrees; a directory’s size is the sum of its contents. - UI toolkits:
java.awt.Containeris aComponentthat contains components; the same for JavaFXParentand HTML’s DOM. - Spring:
CompositeCacheManager,CompositePropertySource,CompositeHealthContributorin Actuator, and Spring Security’sDelegatingAuthenticationEntryPointtreat many delegates as one. - Compilers and query languages: abstract syntax trees, such as the rule tree in the Interpreter example.
Interview questions and answers#
What is the Composite pattern? A structural pattern that composes objects into trees and gives leaves and composites a common interface, so clients treat them uniformly.
What is the difference between transparency and safety in Composite? Transparency puts child-management methods on the component so all nodes look alike; safety puts them only on composites so the compiler prevents misuse.
How does Composite relate to Decorator? Both use recursive composition. A decorator wraps exactly one component to add behaviour; a composite holds many children to aggregate them.
Give a JDK example.
java.awt.Container extends Component and holds child components.
Summary#
- Composite represents part-whole hierarchies as trees.
- Leaves and composites share one interface; composites delegate to children.
- Prefer the safe variant and sealed interfaces in modern Java.
- Common in files, UI trees, ASTs and “composite” Spring infrastructure classes.
Related topics#
- Visitor Pattern — operations over composite trees
- Iterator Pattern — traversing them
- Decorator Pattern
- Compound patterns and MVC — the view in MVC is a composite
References#
- Gamma, Helm, Johnson, Vlissides. Design Patterns. Addison-Wesley, 1994. Composite, p. 163.
- Eric Freeman, Elisabeth Robson. Head First Design Patterns (2nd edition). O’Reilly, 2020. Chapter 9 (menus and menu items).