Skip to main content

Composite Pattern

Compose objects into tree structures to represent part-whole hierarchies

Pattern Overview

🌳 Composite Pattern

The Composite Pattern allows you to compose objects into tree structures to represent part-whole hierarchies. It lets clients treat individual objects and compositions of objects uniformly.

Core Concepts

πŸ”Ή Component Interface - Common interface for all objects in the tree
πŸ”Ή Leaf - Individual objects with no children
πŸ”Ή Composite - Objects that can contain other components
πŸ”Ή Uniform Treatment - Same operations work on both leaves and composites

Real-World Applications

File Systems - Files and folders both support operations like size calculation UI Components - Individual elements and containers both render content Expression Trees - Numbers and operations both evaluate to values Organization Charts - Employees and departments both have hierarchical operations

Implementation Benefits

βœ… Simplifies client code - Same interface for simple and complex objects
βœ… Easy to add new components - Just implement the component interface
βœ… Recursive operations - Operations naturally work on entire trees
βœ… Flexible structure - Can build complex hierarchies dynamically

Examples:
Calculate total size of a project directory with nested folders and files
Input:
const project = createFileSystem();
console.log(project.display());
console.log(`Total size: ${project.getSize()}KB`);
Output:
πŸ“ project/ (7KB total)
  πŸ“ src/ (4KB total)
    πŸ“ components/ (3.5KB total)
      πŸ“„ Button.tsx (2KB)
      πŸ“„ Input.tsx (1.5KB)
    πŸ“„ index.ts (0.5KB)
  πŸ“„ package.json (1KB)
  πŸ“„ README.md (2KB)
Total size: 7KB
Render a complex UI structure with nested containers and components
Input:
const app = createUITree();
console.log(app.render());
Output:
<div><header><button>Home</button><button>About</button></header><main><section></section></main></div>
Build and evaluate mathematical expressions as tree structures
Input:
const expr = createExpressionTree();
console.log(`Expression: ${expr.toString()}`);
console.log(`Result: ${expr.evaluate()}`);
Output:
Expression: ((3 + 4) * (2 - 1))
Result: 7

Concepts

design patternssoftware architecturecode organizationobject-oriented programming

Complexity Analysis

Time:O(n)
Space:O(h)

Implementation

file-system

Time: O(n) | Space: O(h)
// File System Composite Implementation
interface FileSystemComponent {
  getName(): string;
  getSize(): number;
  display(indent?: string): string;
}

class File implements FileSystemComponent {
  constructor(private name: string, private size: number) {}

  getName(): string {
    return this.name;
  }

  getSize(): number {
    return this.size;
  }

  display(indent = ''): string {
    return `${indent}πŸ“„ ${this.name} (${this.size}KB)`;
  }
}

class Folder implements FileSystemComponent {
  private children: FileSystemComponent[] = [];

  constructor(private name: string) {}

  getName(): string {
    return this.name;
  }

  getSize(): number {
    return this.children.reduce((total, child) => total + child.getSize(), 0);
  }

  add(component: FileSystemComponent): void {
    this.children.push(component);
  }

  display(indent = ''): string {
    let result = `${indent}πŸ“ ${this.name}/ (${this.getSize()}KB total)`;
    for (const child of this.children) {
      result += '
' + child.display(indent + '  ');
    }
    return result;
  }
}

Β© 2025 John Dilig. Built with Next.js & TypeScript. Open Source (MIT) β€’ Wiki

v... β€’ Auto-versioned