Composite: Treating Individual Objects and Groups Uniformly
Design Patterns Explained: From Theory to Practice: Article 9
As applications grow, information is often organised into increasingly complex hierarchies.
In a ticket-management application, for example, tickets might belong to teams, teams might belong to departments, and departments might form part of a wider support organisation.
At first, working with individual tickets is straightforward. We can retrieve a ticket, inspect its status and calculate whether it is still active.
However, what happens when we need to perform the same operation on an entire team or department?
We could write separate logic for individual tickets and groups of tickets. As the hierarchy grows, that approach can lead to increasingly complicated conditional statements and code that needs to understand the structure of every group.
This is where the Composite pattern becomes useful.
What is the Composite pattern?
Composite is a structural design pattern that allows us to compose objects into tree structures while treating individual objects and groups of objects uniformly.
The central idea is that both an individual object and a collection of objects expose a common interface.
The individual object performs the operation itself, while the composite object delegates that operation to its children and combines their results.
For example, a TicketLeaf represents an individual ticket, while a TicketGroup represents a collection of tickets or other groups.
Both implement the same interface, allowing application code to request the number of active tickets without needing to know whether it is working with one ticket, a team or an entire department.
This is particularly useful when modelling part-whole hierarchies, where larger structures are built from smaller components.
Understanding the participants
The Composite pattern has four main participants:
| Participant | Responsibility |
|---|---|
| Component | Defines the common interface shared by individual objects and groups. |
| Leaf | Represents an individual object that has no children and performs the actual operation. |
| Composite | Represents a group of components. It stores child components and delegates operations to them. |
| Client | Works with components through the common interface without depending on their concrete types. |
In our ticket-management example:
- Component:
ITicketComponentdefines the operation for counting active tickets. - Leaf:
TicketLeafrepresents an individual ticket and determines whether it is active. - Composite:
TicketGroupcontains individual tickets and other groups, combining their results. - Client: A dashboard or reporting service uses
ITicketComponentwithout needing to distinguish between individual tickets and groups.
The important detail is that a composite can contain both leaves and other composites. This allows us to build nested structures without imposing a fixed hierarchy.
Implementing Composite in C#
Let's implement this using a simple ticket-management example.
Our requirement is to calculate the number of active tickets within a particular scope, whether that scope represents an individual ticket, a team or an entire support organisation.
For this example, a ticket is considered active when its status is either Open or InProgress.
1. Define the component interface and ticket model
We start by defining the ticket status and a simple ticket model.
public enum TicketStatus
{
Open,
InProgress,
Resolved
}
public sealed record Ticket(
string Reference,
string Title,
TicketStatus Status);
Next, we define the component interface.
public interface ITicketComponent
{
int CountActiveTickets();
}
This interface represents the operation that makes sense for both individual tickets and groups of tickets.
Notice that we are not including methods such as Add() or Remove() in the interface. These operations are meaningful for groups, but not for individual tickets.
We'll return to this design decision when discussing the trade-offs of the pattern.
2. Create the leaf class
The leaf represents an individual ticket.
It implements ITicketComponent and performs the operation directly because it has no child components to delegate to.
public sealed class TicketLeaf : ITicketComponent
{
private readonly Ticket _ticket;
public TicketLeaf(Ticket ticket)
{
ArgumentNullException.ThrowIfNull(ticket);
_ticket = ticket;
}
public int CountActiveTickets()
{
return _ticket.Status is
TicketStatus.Open or TicketStatus.InProgress
? 1
: 0;
}
}
The implementation is straightforward.
An open or in-progress ticket contributes 1 to the count, while a resolved ticket contributes 0.
The important point is that the leaf implements the same interface as the composite, even though its internal behaviour is different.
3. Create the composite class
Now we create TicketGroup, which represents a collection of tickets or other groups.
Unlike the leaf, the composite maintains a collection of child components.
public sealed class TicketGroup : ITicketComponent
{
private readonly List<ITicketComponent> _children = new();
public string Name { get; }
public TicketGroup(string name)
{
Name = name;
}
public void Add(ITicketComponent component)
{
ArgumentNullException.ThrowIfNull(component);
if (ReferenceEquals(component, this) ||
component is TicketGroup group &&
group.Contains(this))
{
throw new InvalidOperationException(
"Adding this component would create a cycle.");
}
_children.Add(component);
}
public bool Remove(ITicketComponent component)
{
return _children.Remove(component);
}
public int CountActiveTickets()
{
return _children.Sum(
child => child.CountActiveTickets());
}
private bool Contains(ITicketComponent component)
{
if (ReferenceEquals(this, component))
{
return true;
}
return _children
.OfType<TicketGroup>()
.Any(child => child.Contains(component));
}
}
There are a few important things happening here.
First, TicketGroup stores its children as ITicketComponent, rather than storing only TicketLeaf objects.
This allows a group to contain individual tickets as well as other groups. It is what makes the recursive tree structure possible.
Second, CountActiveTickets() delegates the operation to each child and uses LINQ's Sum() to combine the results.
If a child is a TicketLeaf, it calculates its own contribution. If it is another TicketGroup, it delegates the operation further down the hierarchy.
This continues until the operation reaches the leaf objects.
The cycle check prevents a group from containing itself, either directly or through one of its descendants. In a production implementation, additional rules may be needed to enforce single-parent ownership and prevent duplicate membership.
4. Build the object hierarchy
We can now compose individual tickets into teams and teams into a larger support organisation.
var customerSupport = new TicketGroup("Customer Support");
var loginTicket = new TicketLeaf(
new Ticket(
"SUP-101",
"Unable to sign in",
TicketStatus.Open));
customerSupport.Add(loginTicket);
customerSupport.Add(
new TicketLeaf(
new Ticket(
"SUP-102",
"Password reset issue",
TicketStatus.InProgress)));
customerSupport.Add(
new TicketLeaf(
new Ticket(
"SUP-103",
"Account access restored",
TicketStatus.Resolved)));
var platformTeam = new TicketGroup("Platform Team");
platformTeam.Add(
new TicketLeaf(
new Ticket(
"PLAT-201",
"API response failure",
TicketStatus.Open)));
platformTeam.Add(
new TicketLeaf(
new Ticket(
"PLAT-202",
"Database connection issue",
TicketStatus.Resolved)));
var operations = new TicketGroup("Operations");
operations.Add(customerSupport);
operations.Add(platformTeam);
The resulting structure looks like this:
Operations
Customer Support
SUP-101 (Open)
SUP-102 (InProgress)
SUP-103 (Resolved)
Platform Team
PLAT-201 (Open)
PLAT-202 (Resolved)
The hierarchy is not restricted to two levels. We could introduce additional departments, teams or subgroups without changing the component interface or the leaf implementation.
5. Use the common interface
Finally, we can use the same interface to work with an individual ticket or the entire organisation.
ITicketComponent individualTicket = loginTicket;
ITicketComponent organisation = operations;
int individualCount =
individualTicket.CountActiveTickets();
int organisationCount =
organisation.CountActiveTickets();
The individual ticket returns 1, while the organisation returns 3.
The organisation's result is calculated by recursively processing its child groups and individual tickets.
Notice what the client does not need to know.
It does not need to check whether the object is a TicketLeaf or a TicketGroup. It simply calls CountActiveTickets() through the shared interface.
That is the central benefit of Composite: the client can work with individual objects and complex structures using the same abstraction.
When should you use the Composite pattern?
Composite is particularly useful when your application needs to represent hierarchical structures and perform common operations across different levels of that hierarchy.
Consider using it in the following situations:
1. When your data naturally forms a tree structure
Examples include organisational structures, file systems, product categories, reporting hierarchies and nested menus.
If a group can contain individual elements as well as other groups, Composite may provide a suitable design.
2. When clients should treat individual objects and groups uniformly
If application code repeatedly checks whether an object is an individual item or a collection before performing an operation, a common component interface may simplify the design.
3. When operations need to be applied recursively
Composite is useful when an operation on a group should be delegated to its children and the results combined.
Examples include calculating totals, counting items, determining whether a group contains unresolved work and aggregating information across an organisation.
However, not every collection needs Composite.
If you simply need to process a flat collection of tickets, a List<Ticket> and LINQ may be sufficient. Introducing a hierarchy of interfaces and classes would add complexity without providing much value.
Advantages and trade-offs
Like other design patterns, Composite offers benefits but also introduces design decisions that need careful consideration.
Advantages
- Simplifies client code: Clients can work with individual objects and groups through the same interface, reducing the need for type checks and conditional logic.
- Supports recursive structures: Groups can contain other groups, making it easier to represent complex hierarchies.
- Extensibility: New leaf or composite types can be introduced without requiring existing client code to understand their concrete implementations, provided they honour the component contract.
- Clearer responsibilities: Individual objects handle their own operations, while composites coordinate the work of their children.
Disadvantages
- Additional complexity: Introducing component interfaces, leaf classes and composite classes may be excessive for simple collections.
- A common interface can become difficult to design: If individual objects and groups have very different responsibilities, finding operations that genuinely make sense for both can lead to an overgeneralised interface.
- Managing the hierarchy requires care: Adding and removing components introduces questions around ownership, duplicate membership, cycles and object lifetime.
- Some operations are only meaningful for composites: Managing child components on the common interface can force leaf objects to implement methods that have no meaningful purpose.
Transparency versus safety
One particularly interesting design decision is where to define the Add() and Remove() operations.
There are two common approaches.
Transparent approach
Place child-management operations on the common component interface.
This gives clients a uniform interface for both using and modifying the hierarchy. However, leaf objects must then implement operations that do not make sense for them, perhaps by throwing exceptions or doing nothing.
Safe approach
Keep child-management operations exclusively on the composite class.
This prevents clients from attempting to add children to individual tickets and keeps the component interface focused on meaningful operations.
The example in this article follows the safe approach.
Neither option is universally correct. The appropriate choice depends on whether uniform access to hierarchy-management operations is more important than preventing invalid operations.
In C#, keeping those operations off the common interface is often a sensible way to respect the Interface Segregation Principle.
Composite in modern .NET applications
Composite is not a feature of the .NET dependency injection container or a framework-specific mechanism. It is an object-oriented design approach that can be implemented using ordinary C# interfaces, classes and collections.
It is particularly relevant when working with hierarchical domain models or presenting nested information in an application.
For example, an ASP.NET Core application might expose an API endpoint that returns active ticket counts for a department. An application service could retrieve the relevant hierarchy, construct or obtain the appropriate component structure, and invoke the common operation.
There is an important practical consideration when using Composite with data stored in a database.
Recursive operations should not accidentally trigger a separate database query for every child group or ticket. That can result in unnecessary database calls and performance problems.
A better approach is to load the required data deliberately, then perform the in-memory operation over the object structure.
The pattern should organise object behaviour, not hide inefficient data access.
Composite vs. Decorator and Iterator
Composite is sometimes confused with Decorator because both patterns use composition and can involve recursive object structures.
However, their intentions are different.
| Pattern | Primary intention | Typical question |
|---|---|---|
| Composite | Organises individual objects and groups into a tree structure that clients can treat uniformly. | How can I treat a single item and a group of items in the same way? |
| Decorator | Adds responsibilities or behaviour to an existing object without changing its interface. | How can I extend an object's behaviour without modifying its class? |
| Iterator | Provides a way to access elements in a collection sequentially without exposing its underlying representation. | How can I traverse this collection without depending on its internal structure? |
Composite and Decorator are structurally similar in some respects, but their purposes differ.
A composite can contain multiple children and combines their results. A decorator typically wraps one component to add behaviour while preserving the component interface.
They can also work together. For example, we could use a decorator to add auditing or caching behaviour to a particular component within a ticket hierarchy.
Iterator can complement Composite by providing a way to traverse the hierarchy without exposing the internal child collections.
Conclusion
Composite is useful when an application needs to represent part-whole relationships and perform common operations across individual objects and groups.
By giving both leaves and composites a shared interface, we can build nested structures while keeping client code independent of their concrete types.
However, the pattern introduces additional abstractions and requires careful management of the object hierarchy. It is most valuable when the structure is genuinely hierarchical and clients benefit from treating its different levels uniformly.
As with the other patterns in this series, the objective is not to introduce more classes simply because a pattern exists. It is to choose a design that makes the application easier to understand, extend and maintain.
In the next article, we'll explore Decorator, a pattern that allows us to add responsibilities to individual objects dynamically without changing their underlying implementation.
Further reading
- Dive Into Design Patterns — Alexander Shvets. See the Structural Design Patterns chapter on Composite.
- Design Patterns in C#, Second Edition — Vaskaran Sarcar. See Chapter 11, Composite Pattern.
Comments
Join the discussionNo comments yet. Be the first to comment.