THN Interview Prep

Template Method (Behavioral)

Intent / problem it solves

Define the skeleton of an algorithm in a method, deferring some steps to subclasses or hooks. Lets subclasses redefine steps without changing the overall flow.

When to use / when NOT

Use when workflows share a stable sequence but steps vary (ETL pipelines, test fixtures).

Avoid when composition with Strategy functions is simpler or when inheritance depth hurts testing.

Structure

Abstract class defines templateMethod() calling hooks; concrete classes override primitive operations.

Loading diagram…

Go example

package main

import "fmt"

type ReportPipeline interface {
	Load() string
	Transform(string) string
	Publish(string)
}

func RunReport(pipeline ReportPipeline) {
	raw := pipeline.Load()
	refined := pipeline.Transform(raw)
	pipeline.Publish(refined)
}

type SalesReport struct{}

func (SalesReport) Load() string                 { return "rows" }
func (SalesReport) Transform(rows string) string { return "csv:" + rows }
func (SalesReport) Publish(payload string)       { fmt.Println(payload) }

func main() {
	RunReport(SalesReport{})
}

JavaScript example

class GameLoop {
  tick() {
    this.captureInput();
    this.updateWorld();
    this.renderFrame();
  }

  captureInput() {
    throw new Error('override');
  }

  updateWorld() {
    throw new Error('override');
  }

  renderFrame() {
    throw new Error('override');
  }
}

class Pong extends GameLoop {
  captureInput() {
    this.input = 'paddle';
  }

  updateWorld() {
    this.ball = 'move';
  }

  renderFrame() {
    console.log(this.input, this.ball);
  }
}

new Pong().tick();

Interview phrase

“Template method nails invariant ordering—parse, validate, persist—while letting subclasses or collaborators swap individual steps.”

Map to LLD for batch jobs, pipelines, or game loops in LLD case studies.

Last updated on

Spotted something unclear or wrong on this page?

On this page