Zachary W. Huang

Home Projects Blog Guides Resume

Composite

Idea: represent objects and their containers the same way to produce uniform tree-like hierarchies. Essentially, this gives objects in a hierarchy the ability to refer (recursively) to all other objects in the same hierarchy.

Connection: A similar idea (sum types) is also found in languages like OCaml (recursive variants) and Haskell (recursive data/types).

class Composite {
  doThing() {};
  addChild(_: Composite) {};
}

class BasicThing extends Composite {
  doThing() {
    console.log("Hi");
  }
}

class ThingContainer extends Composite {
  things: Composite[] = []

  doThing() {
    for (let thing of this.things) {
      thing.doThing();
    }
  }

  addChild(c: Composite) {
    this.things.push(c);
  }
}

function main() {
  const container = new ThingContainer();
  container.addChild(new BasicThing());
  container.addChild(new BasicThing());
  container.addChild(new BasicThing());
  container.doThing(); // "Hi  Hi Hi"
}
RSS icon github logo linkedin logo

Zachary W. Huang © 2021-2024