Template Method

Posted by Dustin Boston .


CAUTION

Construction Area
Watch out for:

  • Broken code
  • No comments
  • Partial examples
  • Missing tests

Source Code Listing

code.ts

abstract class AbstractClass {
  templateMethod(): void {
    this.primitiveOperation1();
    this.primitiveOperation2(); // No need to return here if void
  }

  abstract primitiveOperation1(): void; // Abstract methods
  abstract primitiveOperation2(): void;
}

class ConcreteClass extends AbstractClass {
  primitiveOperation1(): void {
    console.log("primitiveOperation1");
  }

  primitiveOperation2(): void {
    console.log("primitiveOperation2");
  }
}

// Static Template Method (using a factory function for better type inference)
class StaticAbstractClass {
  static templateMethod<T extends StaticAbstractClass>(
    this: new () => T,
  ): void {
    const cls = new this();
    cls.primitiveOperation1();
    cls.primitiveOperation2();
  }

  primitiveOperation1(): void {
    // Default implementations
  }

  primitiveOperation2(): void {
    // Implement this method
  }
}

class StaticConcreteClass extends StaticAbstractClass {
  primitiveOperation1(): void {
    console.log("primitiveOperation1");
  }

  primitiveOperation2(): void {
    console.log("primitiveOperation2");
  }
}

const example = {
  run(): void {
    const concrete = new ConcreteClass();
    concrete.templateMethod();

    StaticConcreteClass.templateMethod();
  },
};

example.run();