Composite

Posted by Dustin Boston .


CAUTION

Construction Area
Watch out for:

  • Broken code
  • No comments
  • Partial examples
  • Missing tests
O p « e L r O A R G e a p d e e a t e d m t f i r ( o C » o C a C v h n o t o e i ( m i m ( l ) p o p C d o n o o ( n ( n m i e ) e p n n n o t t t n ) ) e O A R G n p d e e t e d m t ) r ( o C C a C v h o t o e i m i m ( l p o p C d o n o o ( s ( n m i i ) e p n t n o t e t n ) ) e n t ) c h i l d r e n

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();