Compose objects into tree structures and let clients treat individual objects and compositions of objects the same way, through one shared interface.
Composite is the pattern you reach for when your data is a tree and you are tired of asking each node whether it is a leaf or a branch. You give single items and groups the same interface. A group answers a question by asking its children, and a leaf answers it directly. In interviews, Composite comes up when you model menus, org charts, permission scopes, pricing bundles or anything else that nests. This guide follows one invented system from start to finish: a cloud cost report that rolls spend up through projects and folders. You will see the problem, the structure, pseudocode and runnable code in TypeScript, Python and PHP.
The problem
A situation where the obvious design starts to hurt.
The platform finance team at Tallyhaus, a mid-sized payments company, maintains an internal tool called SpendTree. It shows how much each part of the company spends on cloud infrastructure every month. The cloud account holds about 1,400 resources (virtual machines, databases, storage buckets, DNS zones) spread across 38 projects, and those projects sit inside 6 business-unit folders. Some folders contain subfolders, so the tree is up to 4 levels deep.
The first version of SpendTree had a Resource class and a Folder class with nothing in common. Every report function looked like this: if the thing is a resource, read its cost; if it is a folder, loop over its children, and for each child check again whether it is a resource or a folder. The same type check appeared in the total-cost function, the resource-count function, the budget-alert function and the CSV export.
Then product asked for a new level: projects inside folders, with their own labels. Adding a Project type meant editing every one of those functions and adding another branch to each type check. One branch was missed in the budget alert, and for a week it silently ignored resources that lived directly inside a project. The code knew too much about the shape of the tree.
The solution
What the pattern proposes.
Composite removes the type checks by giving every node in the tree the same interface. In SpendTree that interface is CostNode, with three methods: name(), cost() and resourceCount().
A Resource is a leaf. It returns its own monthly cost in cents and reports a count of 1. A Group is a composite. It holds a list of CostNode children and answers every question by delegating to them: its cost is the sum of its children's costs, and its count is the sum of their counts. Because children are typed as CostNode, a group can hold resources, other groups, or a mix of both, at any depth.
Folders and projects become instances of Group with different names, so the new level no longer requires a new class. The report code takes a CostNode and calls cost() on it. It does not care whether it received the whole organisation, one project or a single database. Recursion happens inside the tree, one level at a time, instead of in every client function.
One design choice to note: add() lives only on Group, not on the shared interface. That is the safe variant of Composite. You cannot accidentally add a child to a leaf, at the cost of needing the concrete Group type when you build the tree.
An everyday analogy
The same idea, outside software.
Think of a household budget kept in envelopes. Some envelopes hold cash for one purpose, such as the gas bill. Others are labelled envelopes that contain smaller envelopes: a Holidays envelope holding one for flights and one for accommodation.
When someone asks how much is set aside for holidays, you do not need a different procedure from the one for the gas bill. You ask the envelope. A plain envelope tells you its cash. A bundle envelope adds up what its inner envelopes say. Whoever asks the question treats every envelope the same way, no matter how many are nested inside.
Structure
The pieces and how they relate.
Participants
- Component (CostNode)
- Declares the operations every node in the tree supports. Clients depend only on this interface, so they never need to know whether they hold a leaf or a group.
- Leaf (Resource)
- A node with no children. It does the real work directly: a resource returns its own monthly cost and counts itself as one resource.
- Composite (Group)
- A node that stores child components and implements each operation by delegating to its children and combining their results. It also exposes add() for building the tree.
- Client (report)
- Builds or receives a tree and calls operations on any CostNode. The same code produces a report for the whole organisation, one project or a single resource.
Pseudocode
The solution to the scenario, language-neutral.
interface CostNode
method name(): string
method cost(): integer // cents per month
method resourceCount(): integer
class Resource implements CostNode
field resourceName
field monthlyCents
method name() = resourceName
method cost() = monthlyCents
method resourceCount() = 1
class Group implements CostNode
field groupName
field children: list of CostNode = empty
method add(child: CostNode)
children.append(child)
return this
method name() = groupName
method cost()
total = 0
for each child in children
total = total + child.cost()
return total
method resourceCount()
total = 0
for each child in children
total = total + child.resourceCount()
return total
function report(node: CostNode)
count = node.resourceCount()
noun = "resource" if count == 1 else "resources"
return node.name() + ": $" + format(node.cost() / 100, 2 decimals) + " across " + count + " " + noun
// build the Tallyhaus tree
checkout = Group("checkout-prod")
.add(Resource("vm-checkout-1", 41250))
.add(Resource("vm-checkout-2", 41250))
.add(Resource("db-orders", 128900))
analytics = Group("analytics")
.add(Resource("bucket-events", 9320))
.add(Resource("warehouse", 215000))
dns = Resource("dns-zone", 50)
org = Group("tallyhaus")
.add(Group("payments").add(checkout))
.add(analytics)
.add(dns)
print report(org) // tallyhaus: $4357.70 across 6 resources
print report(checkout) // checkout-prod: $2114.00 across 3 resources
print report(dns) // dns-zone: $0.50 across 1 resourceThe code
The same solution in TypeScript, Python and PHP.
interface CostNode {
name(): string;
cost(): number; // cents per month
resourceCount(): number;
}
class Resource implements CostNode {
constructor(
private readonly resourceName: string,
private readonly monthlyCents: number,
) {}
name(): string {
return this.resourceName;
}
cost(): number {
return this.monthlyCents;
}
resourceCount(): number {
return 1;
}
}
class Group implements CostNode {
private readonly children: CostNode[] = [];
constructor(private readonly groupName: string) {}
add(child: CostNode): this {
this.children.push(child);
return this;
}
name(): string {
return this.groupName;
}
cost(): number {
return this.children.reduce((sum, child) => sum + child.cost(), 0);
}
resourceCount(): number {
return this.children.reduce((sum, child) => sum + child.resourceCount(), 0);
}
}
function report(node: CostNode): string {
const count = node.resourceCount();
const noun = count === 1 ? "resource" : "resources";
return `${node.name()}: $${(node.cost() / 100).toFixed(2)} across ${count} ${noun}`;
}
const checkout = new Group("checkout-prod")
.add(new Resource("vm-checkout-1", 41250))
.add(new Resource("vm-checkout-2", 41250))
.add(new Resource("db-orders", 128900));
const analytics = new Group("analytics")
.add(new Resource("bucket-events", 9320))
.add(new Resource("warehouse", 215000));
const dns = new Resource("dns-zone", 50);
const org = new Group("tallyhaus")
.add(new Group("payments").add(checkout))
.add(analytics)
.add(dns);
console.log(report(org)); // tallyhaus: $4357.70 across 6 resources
console.log(report(checkout)); // checkout-prod: $2114.00 across 3 resources
console.log(report(dns)); // dns-zone: $0.50 across 1 resourcefrom __future__ import annotations
from abc import ABC, abstractmethod
class CostNode(ABC):
@abstractmethod
def name(self) -> str: ...
@abstractmethod
def cost(self) -> int: # cents per month
...
@abstractmethod
def resource_count(self) -> int: ...
class Resource(CostNode):
def __init__(self, resource_name: str, monthly_cents: int) -> None:
self._resource_name = resource_name
self._monthly_cents = monthly_cents
def name(self) -> str:
return self._resource_name
def cost(self) -> int:
return self._monthly_cents
def resource_count(self) -> int:
return 1
class Group(CostNode):
def __init__(self, group_name: str) -> None:
self._group_name = group_name
self._children: list[CostNode] = []
def add(self, child: CostNode) -> Group:
self._children.append(child)
return self
def name(self) -> str:
return self._group_name
def cost(self) -> int:
return sum(child.cost() for child in self._children)
def resource_count(self) -> int:
return sum(child.resource_count() for child in self._children)
def report(node: CostNode) -> str:
count = node.resource_count()
noun = "resource" if count == 1 else "resources"
return f"{node.name()}: ${node.cost() / 100:.2f} across {count} {noun}"
checkout = (
Group("checkout-prod")
.add(Resource("vm-checkout-1", 41250))
.add(Resource("vm-checkout-2", 41250))
.add(Resource("db-orders", 128900))
)
analytics = (
Group("analytics")
.add(Resource("bucket-events", 9320))
.add(Resource("warehouse", 215000))
)
dns = Resource("dns-zone", 50)
org = (
Group("tallyhaus")
.add(Group("payments").add(checkout))
.add(analytics)
.add(dns)
)
print(report(org)) # tallyhaus: $4357.70 across 6 resources
print(report(checkout)) # checkout-prod: $2114.00 across 3 resources
print(report(dns)) # dns-zone: $0.50 across 1 resource<?php
declare(strict_types=1);
interface CostNode
{
public function name(): string;
public function cost(): int; // cents per month
public function resourceCount(): int;
}
final class Resource implements CostNode
{
public function __construct(
private readonly string $resourceName,
private readonly int $monthlyCents,
) {
}
public function name(): string
{
return $this->resourceName;
}
public function cost(): int
{
return $this->monthlyCents;
}
public function resourceCount(): int
{
return 1;
}
}
final class Group implements CostNode
{
/** @var CostNode[] */
private array $children = [];
public function __construct(private readonly string $groupName)
{
}
public function add(CostNode $child): static
{
$this->children[] = $child;
return $this;
}
public function name(): string
{
return $this->groupName;
}
public function cost(): int
{
return array_sum(array_map(fn (CostNode $child): int => $child->cost(), $this->children));
}
public function resourceCount(): int
{
return array_sum(array_map(fn (CostNode $child): int => $child->resourceCount(), $this->children));
}
}
function report(CostNode $node): string
{
$count = $node->resourceCount();
$noun = $count === 1 ? 'resource' : 'resources';
return sprintf('%s: $%.2f across %d %s', $node->name(), $node->cost() / 100, $count, $noun);
}
$checkout = (new Group('checkout-prod'))
->add(new Resource('vm-checkout-1', 41250))
->add(new Resource('vm-checkout-2', 41250))
->add(new Resource('db-orders', 128900));
$analytics = (new Group('analytics'))
->add(new Resource('bucket-events', 9320))
->add(new Resource('warehouse', 215000));
$dns = new Resource('dns-zone', 50);
$org = (new Group('tallyhaus'))
->add((new Group('payments'))->add($checkout))
->add($analytics)
->add($dns);
echo report($org), PHP_EOL; // tallyhaus: $4357.70 across 6 resources
echo report($checkout), PHP_EOL; // checkout-prod: $2114.00 across 3 resources
echo report($dns), PHP_EOL; // dns-zone: $0.50 across 1 resourceWhen to use it
Situations where it pays off.
Your domain is naturally a part-whole hierarchy: folders and files, menus and menu items, bundles and products, teams and people.
Composite models the hierarchy directly. Each node knows its own children, so the tree's shape lives in the data rather than in nested loops scattered across the codebase.
Client code keeps branching on whether it holds a single item or a group, and the same type checks repeat in several functions.
A shared interface replaces those checks with polymorphic calls. New operations are written once on each node type instead of once per client, with a branch for every kind of node.
The tree's depth is not fixed, or a new nesting level could be added later.
Since a group can contain other groups, the code handles 2 levels and 10 levels the same way. In SpendTree, adding projects under folders needed no new class.
You want to run the same operation on any subtree: the whole organisation, one department or one item.
Every node, including the root, is a valid entry point. A report on one project uses exactly the same call as a report on the whole company.
How to implement it
Steps to introduce it in existing code.
Confirm that your model really is a tree, where groups contain items or other groups and the operations you need make sense for both.
Define the component interface with only the operations clients need on every node, such as
cost()andresourceCount(). Keep it small.Write the leaf class. It implements each operation with its own data and has no children.
Write the composite class. Give it a list of children typed as the component interface, plus methods to add and, if needed, remove children.
Implement each composite operation by delegating to the children and combining their results, for example by summing, taking a maximum or concatenating.
Decide where child-management methods live. Put
add()only on the composite for type safety, or on the component interface for full transparency, and document the choice.Change client code to depend on the component interface, then delete the old type checks.
Pros and cons
What you gain and what you pay.
Pros
- Clients treat a single item and a whole subtree the same way, which removes repeated leaf-or-group branching.
- New kinds of leaves or groups can be added without changing client code, in line with the open/closed principle.
- Recursive operations live in one place: each node handles its own level and delegates the rest.
- Any node can serve as an entry point, so reports on part of a tree come for free.
Cons
- A shared interface can become too general. Operations that only make sense for groups, such as
add(), either leak onto leaves or force clients to downcast. - It is harder to restrict what a group may contain, for example to stop a resource from holding a folder, because everything is the same type. You need runtime checks for such rules.
- Naive recursive operations recompute the whole subtree on every call. On large trees that are queried often, you may need caching and cache invalidation.
- Nothing in the pattern prevents cycles. If a group is added to its own descendant, recursive calls will never terminate unless you guard against it.
Relations with other guides
Patterns it's often confused or combined with.
- Decorator: Add Behaviour by Wrapping, the Way Middleware Does
Decorator has a similar recursive structure, but a decorator wraps exactly one component to add behaviour, while a composite holds many children and combines their results.
- Iterator Pattern: Walk Any Collection Without Knowing Its Shape
Use an Iterator to walk a composite tree depth-first or breadth-first without exposing how each group stores its children.
- Visitor Pattern: Add Operations Without Editing Your Classes
When you keep adding new operations over a stable composite tree, a Visitor lets you add them without editing every node class.
- Chain of Responsibility: Pass a Request Along Until One Handles It
Composite trees often pair with Chain of Responsibility: a request that a leaf cannot handle is passed up to its parent group.
- Builder Pattern: Assemble Complex Objects Step by Step
A Builder can assemble complex composite trees step by step, hiding the nested add() calls from the client.
- Flyweight Pattern: Share Immutable State Across Many Objects
If a tree contains many identical leaves, sharing them as flyweights can save memory, as long as leaves do not store a reference to their parent.
Common questions
Short answers to the usual doubts.
Should add() and remove() be on the component interface or only on the composite?
Both are valid, and interviewers like hearing you name the trade-off. Putting them on the interface (the transparent variant) means clients never need the concrete type, but leaves must either throw or silently ignore the call. Putting them only on the composite (the safe variant, used in this guide) lets the compiler stop you from adding children to a leaf, at the cost of needing the concrete Group type when you build the tree.
What is the time complexity of cost() on the root?
Each node is visited once, so it is O(n) in the number of nodes in the subtree, and the recursion depth equals the tree's height. If the root is queried far more often than the tree changes, you can cache totals in each group and invalidate the cache up the parent chain on every change. That makes reads O(1) but adds work and complexity to every write.
How do I stop someone from creating a cycle?
The pattern itself does not prevent it. A common guard is to check, inside add(), that the new child is not the group itself or one of its ancestors. That requires parent references or a walk over the child's subtree. Another option is to build trees only through a factory or builder that enforces the rule. Without a guard, a cycle makes recursive calls run until the stack overflows.
Is Composite the same as just using recursion on a tree?
Recursion is the mechanism, and Composite is about where it lives. With plain recursion, a client function walks the tree and branches on node types. With Composite, each node class knows how to answer for itself, so the recursion is spread across polymorphic methods and clients make one call on whatever node they hold.
When is Composite overkill?
If your hierarchy has a fixed, shallow shape, such as orders that always contain line items and never nest further, two plain classes with a simple loop are clearer. Composite pays off when nesting depth varies, when groups can contain groups, or when many client functions would otherwise repeat the same leaf-or-group checks.