Zachary W. Huang

Home Projects Blog Guides Resume

Template Method

Idea: allow a subclass to redefine the steps of an algorithm by overriding certain (“template”) methods.

abstract class Thing {
  abstract primitiveA(): number;
  abstract primitiveB(i: number): void;

  doThing() {
    for (let i = 0; i < this.primitiveA(); i++) {
      this.primitiveB(i);
    }
  }
}

class ThingA extends Thing {
  primitiveA(): number {
    return 5;
  }
  primitiveB(i: number) {
    console.log(i + 1)
  }
}

class ThingB extends Thing {
  primitiveA(): number {
    return 3;
  }
  primitiveB(i: number) {
    console.log(10 + i * 10)
  }
}

function main() {
  const thingA = new ThingA();
  thingA.doThing(); // "1  2  3  4  5"
  const thingB = new ThingB();
  thingB.doThing(); // "10  20  30"
}
RSS icon github logo linkedin logo

Zachary W. Huang © 2021-2024