StructuralC#verifiedVerified

Composite Pattern in C#

Composes objects into tree structures to represent part-whole hierarchies, letting clients treat individual objects and compositions uniformly.

How to Implement the Composite Pattern in C#

1Step 1: Component interface shared by leaves and composites

public interface IFileSystemItem
{
    string Name { get; }
    long GetSize();
}

2Step 2: Leaf node

public class File(string name, long size) : IFileSystemItem
{
    public string Name => name;
    public long GetSize() => size;
}

3Step 3: Composite node contains children

public class Directory(string name) : IFileSystemItem
{
    private readonly List<IFileSystemItem> _children = [];

    public string Name => name;

    public void Add(IFileSystemItem item) => _children.Add(item);
    public void Remove(IFileSystemItem item) => _children.Remove(item);

    // Recursively compute size
    public long GetSize() => _children.Sum(c => c.GetSize());
}

// Usage:
// var root = new Directory("root");
// root.Add(new File("a.txt", 100));
// var sub = new Directory("sub");
// sub.Add(new File("b.txt", 200));
// root.Add(sub);
// Console.WriteLine(root.GetSize()); // 300

Composite Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Composite Pattern in the Real World

A company’s org chart is a composite structure. An individual employee (leaf) has a salary and a name. A department (composite) also has a name and a budget—calculated by summing the salaries of all its members, which may themselves be other departments. HR can call ‘get budget’ on the CEO’s node and the entire tree is summed recursively.