· Last updated on

[Structural] Composite

typescriptdesign-pattern

Problems

Bridge pattern

Tree is a data structure focus on saving and retrieving data. In the meantime, Composite purpose to create a structure for each object.

Steps:

Examples:

  1. Init Component
interface IComponent {
  operation(): void;
  add(child: IComponent): void;
  remove(child: IComponent): void;
  getChild(index: number): IComponent | undefined;
}
  1. Init node
class Leaf implements IComponent {
  constructor(public name: string) {}

  operation(): void {
    console.log(`Leaf operation ${this.name}`);
  }

  add(child: IComponent): void {
    throw new Error("Method not implemented.");
  }
  remove(child: IComponent): void {
    throw new Error("Method not implemented.");
  }
  getChild(index: number): IComponent | undefined {
    return undefined;
  }
}
  1. Init Composite
class Composite implements IComponent {
  children: IComponent[] = [];
  constructor(public name: string) {}

  operation(): void {
    console.log(`Operation on ${this.name}`);
    for (const child of this.children) {
      child.operation();
    }
  }

  add(child: IComponent): void {
    this.children.push(child);
  }
  remove(child: IComponent): void {
    const index = this.children.indexOf(child);
    if (index !== -1) {
      this.children.splice(index, 1);
    }
  }
  getChild(index: number): IComponent | undefined {
    return this.children[index];
  }
}
  1. Assign node into Composite
const root = new Composite("Root");
const leaf1 = new Leaf("Leaf 1");
const leaf2 = new Leaf("Leaf 2");

const composite = new Composite("Composite1");
const leaf3 = new Leaf("Leaf 3");
const leaf4 = new Leaf("Leaf 4");
  1. Retrieve data
root.add(composite);
root.add(leaf1);
root.add(leaf2);
composite.add(leaf3);
composite.add(leaf4);

console.log(root.operation());

Conclusions