Composite Pattern

Posted by Dustin Boston in .

The Composite Pattern is a structural design pattern that enables you to compose objects into tree structures to represent part-whole hierarchies, simplifying the management of complex object structures.


The Composite Pattern is a structural design pattern that enables you to compose objects into tree structures to represent part-whole hierarchies. This pattern simplifies the management of complex object structures by allowing clients to treat individual objects and compositions of objects uniformly. It is particularly useful for scenarios involving recursive or hierarchical data.

Source Code Listing

code.ts

type Component = {
  operation(): void;
  add(component: Component): void;
  getComposite(): Component | undefined;
};

class Leaf implements Component {
  operation(): void {
    console.log("Leaf operation");
  }

  add(_component: Component): void {
    throw new Error("Cannot add to a leaf");
  }

  getComposite(): Component | undefined {
    return undefined;
  }
}

class Composite implements Component {
  private readonly list: Component[] = [];

  operation(): void {
    console.log("Composite operation:");
    for (const component of this.list) {
      component.operation(); // Delegate to children
    }
  }

  add(component: Component): void {
    this.list.push(component);
  }

  getComposite(): Component {
    return this;
  }
}

const client = {
  run(): void {
    const composite = new Composite();
    const leaf = new Leaf();
    composite.add(leaf);
    composite.operation();

    const composite2 = new Composite();
    composite.add(composite2);
    composite.operation();

    const composite3 = new Composite();
    const leaf2 = new Leaf();
    const leaf3 = new Leaf();
    composite3.add(leaf2);
    composite3.add(leaf3);
    composite.add(composite3); // Add a more complex composite
    composite.operation();
  },
};

client.run();