Skip to content Skip to footer

Composite Design Pattern: Building Tree Structures

You’re building a file system explorer. Files are simple objects, but directories can contain both files and other directories. How do you write code that treats individual files and entire directory trees uniformly? The Composite pattern solves this by letting you compose objects into tree structures and work with them as if they were individual objects.

Problem

Consider a company organizational chart where employees can be individual workers or managers who have subordinates:

public class Employee
{
    public string Name { get; set; }
    public decimal Salary { get; set; }

    public decimal GetTotalSalary()
    {
        return Salary;
    }
}

public class Manager
{
    public string Name { get; set; }
    public decimal Salary { get; set; }
    public List<Employee> Subordinates { get; set; } = new();

    public decimal GetTotalSalary()
    {
        decimal total = Salary;
        foreach (var employee in Subordinates)
        {
            total += employee.GetTotalSalary();
        }
        return total;
    }
}

This approach has problems:

  • You need separate handling for Employee and Manager
  • You can’t have managers managing other managers easily
  • Code that works with employees must check types and handle them differently
  • Adding new types (like teams or departments) requires changes everywhere

Solution

The Composite pattern composes objects into tree structures to represent part-whole hierarchies. It lets clients treat individual objects and compositions uniformly.

Definition: The Composite pattern lets you compose objects into tree structures and then work with these structures as if they were individual objects.

The pattern has three main components:

  • Component: The common interface for all objects in the composition
  • Leaf: Represents individual objects (no children)
  • Composite: Represents objects that have children

Pseudocode

Component (IEmployee)
    ↓ implemented by
Leaf (Employee) and Composite (Manager)
    ↓ Composite contains
List<Component>

Examples

Here’s a complete, runnable C# implementation:

using System;
using System.Collections.Generic;
using System.Linq;

// Component interface
public interface IEmployee
{
    string Name { get; }
    decimal GetSalary();
    void Display(string indent = "");
}

// Leaf - represents individual employee
public class Employee : IEmployee
{
    public string Name { get; set; }
    public decimal Salary { get; set; }

    public Employee(string name, decimal salary)
    {
        Name = name;
        Salary = salary;
    }

    public decimal GetSalary()
    {
        return Salary;
    }

    public void Display(string indent = "")
    {
        Console.WriteLine($"{indent}- {Name} (${Salary})");
    }
}

// Composite - represents manager with subordinates
public class Manager : IEmployee
{
    public string Name { get; set; }
    public decimal Salary { get; set; }
    private List<IEmployee> _subordinates = new();

    public Manager(string name, decimal salary)
    {
        Name = name;
        Salary = salary;
    }

    public void Add(IEmployee employee)
    {
        _subordinates.Add(employee);
    }

    public void Remove(IEmployee employee)
    {
        _subordinates.Remove(employee);
    }

    public decimal GetSalary()
    {
        return Salary + _subordinates.Sum(e => e.GetSalary());
    }

    public void Display(string indent = "")
    {
        Console.WriteLine($"{indent}+ {Name} (${Salary})");
        foreach (var subordinate in _subordinates)
        {
            subordinate.Display(indent + "  ");
        }
    }
}

// Usage
class Program
{
    static void Main()
    {
        // Create individual employees
        var dev1 = new Employee("John", 80000);
        var dev2 = new Employee("Jane", 85000);
        var designer = new Employee("Bob", 70000);

        // Create managers
        var techLead = new Manager("Alice", 120000);
        techLead.Add(dev1);
        techLead.Add(dev2);

        var designManager = new Manager("Charlie", 110000);
        designManager.Add(designer);

        // Create top-level manager
        var ceo = new Manager("David", 200000);
        ceo.Add(techLead);
        ceo.Add(designManager);

        // Treat all uniformly
        Console.WriteLine("Organizational Structure:");
        ceo.Display();

        Console.WriteLine($"\nTotal Company Salary: ${ceo.GetSalary():N0}");
    }
}

Output:

Organizational Structure:
+ David ($200000)
  + Alice ($120000)
    - John ($80000)
    - Jane ($85000)
  + Charlie ($110000)
    - Bob ($70000)

Total Company Salary: $665,000

Real-World Example: File System

// Component
public interface IFileSystemItem
{
    string Name { get; }
    long GetSize();
    void Display(string indent = "");
}

// Leaf
public class File : IFileSystemItem
{
    public string Name { get; set; }
    public long Size { get; set; }

    public File(string name, long size)
    {
        Name = name;
        Size = size;
    }

    public long GetSize() => Size;

    public void Display(string indent = "")
    {
        Console.WriteLine($"{indent}📄 {Name} ({Size} bytes)");
    }
}

// Composite
public class Directory : IFileSystemItem
{
    public string Name { get; set; }
    private List<IFileSystemItem> _items = new();

    public Directory(string name)
    {
        Name = name;
    }

    public void Add(IFileSystemItem item)
    {
        _items.Add(item);
    }

    public void Remove(IFileSystemItem item)
    {
        _items.Remove(item);
    }

    public long GetSize()
    {
        return _items.Sum(item => item.GetSize());
    }

    public void Display(string indent = "")
    {
        Console.WriteLine($"{indent}📁 {Name}/");
        foreach (var item in _items)
        {
            item.Display(indent + "  ");
        }
    }
}

// Usage
var root = new Directory("Root");
var documents = new Directory("Documents");
var photos = new Directory("Photos");

documents.Add(new File("report.pdf", 1024000));
documents.Add(new File("notes.txt", 2048));

photos.Add(new File("vacation.jpg", 2048000));
photos.Add(new File("family.jpg", 1536000));

root.Add(documents);
root.Add(photos);
root.Add(new File("readme.txt", 512));

root.Display();
Console.WriteLine($"\nTotal Size: {root.GetSize()} bytes");

Applications

Enterprise Use Cases:

  1. File Systems: Representing files and directories uniformly
  2. UI Component Trees: Treating individual components and containers the same way (buttons, panels, windows)
  3. Organizational Charts: Representing employees, managers, and departments
  4. Menu Systems: Handling menu items and submenus uniformly
  5. Expression Trees: Building and evaluating mathematical or logical expressions
  6. Document Structures: Representing paragraphs, sections, and entire documents
  7. Product Catalogs: Handling individual products and product categories
  8. Permission Systems: Representing individual permissions and permission groups

Benefits:

  • Simplifies client code by treating individual objects and compositions uniformly
  • Makes it easy to add new types of components
  • Allows you to work with complex tree structures more simply
  • Follows the Open/Closed Principle
  • Enables recursive operations on tree structures

When to Use:

  • You need to represent part-whole hierarchies
  • You want clients to ignore the difference between individual objects and compositions
  • You need to perform operations on entire tree structures
  • The structure can be nested to any depth

Key Insight: The Composite pattern is about treating individual objects and groups of objects uniformly. Whether you’re working with a single file or an entire directory tree, the interface remains the same, making your code simpler and more maintainable.

Leave a Comment