Template Method
Define the skeleton of an algorithm in a base class, letting subclasses override certain steps without changing its structure.
- 5 animated steps
- 6 languages
- Behavioral patterns
The problem
Importing CSV, JSON or Excel always follows the same steps: open, parse, validate, save. Only the parsing changes, yet every importer duplicates everything else.
The solution
Write a "template" method (run()) that chains the steps in a fixed order. Variable steps are abstract; optional steps are "hooks" with a default behavior.
The pattern in action
- Client
- Key role of the pattern
- Object
- Data or state
- run() chains the steps in a fixed order. Shared step: open().
- parse() is abstract: it depends on the format.
- The CsvImporter subclass provides its own implementation.
- validate() is a hook: default behavior, overridable.
- save() is shared. Only the format changes, everything else is reused.
An analogy
A standard house plan: foundations, walls and roof are imposed, but each client chooses their own tiling and windows.
When to use it
- Algorithms with a fixed structure and variable steps
- Frameworks: lifecycles (setUp/tearDown, hooks)
- Multi-format imports / exports
Pros and cons
Pros
- Eliminates duplication
- Step order guaranteed
- Clear extension points
Cons
- Based on inheritance (rigid)
- The skeleton can constrain subclasses
- Possible Liskov violation if a hook is badly overridden
Implementations
The same example, written idiomatically in each language.
Template Method in Python
import csv
import json
from abc import ABC, abstractmethod
class DataImporter(ABC):
def run(self, path: str) -> None: # the template method
raw = self.open(path)
rows = self.parse(raw)
rows = [r for r in rows if self.validate(r)]
self.save(rows)
def open(self, path: str) -> str:
with open(path, encoding="utf-8") as f:
return f.read()
@abstractmethod
def parse(self, raw: str) -> list[dict]: ...
def validate(self, row: dict) -> bool: # hook: optional override
return bool(row.get("email"))
def save(self, rows: list[dict]) -> None:
print(f"{len(rows)} rows imported")
class CsvImporter(DataImporter):
def parse(self, raw): return list(csv.DictReader(raw.splitlines()))
class JsonImporter(DataImporter):
def parse(self, raw): return json.loads(raw)
CsvImporter().run("clients.csv")
Template Method in TypeScript
import { promises as fs } from "node:fs";
type Row = Record<string, string>;
abstract class DataImporter {
// template method
async run(path: string) {
const raw = await this.open(path);
const rows = this.parse(raw).filter((r) => this.validate(r));
await this.save(rows);
}
protected open(path: string) { return fs.readFile(path, "utf8"); }
protected abstract parse(raw: string): Row[];
protected validate(row: Row) { return Boolean(row.email); } // hook
protected async save(rows: Row[]) { console.log(rows.length + " rows imported"); }
}
class JsonImporter extends DataImporter {
protected parse(raw: string): Row[] { return JSON.parse(raw); }
}
await new JsonImporter().run("clients.json");
Template Method in Java
abstract class DataImporter {
// final: subclasses cannot change the order of the steps
public final void run(Path path) throws IOException {
String raw = Files.readString(path);
List<Map<String, String>> rows = parse(raw).stream()
.filter(this::validate)
.toList();
save(rows);
}
protected abstract List<Map<String, String>> parse(String raw);
protected boolean validate(Map<String, String> row) { // hook
return row.get("email") != null;
}
protected void save(List<Map<String, String>> rows) {
System.out.println(rows.size() + " rows imported");
}
}
class CsvImporter extends DataImporter {
@Override
protected List<Map<String, String>> parse(String raw) {
/* split into rows / columns */
return List.of();
}
}
Template Method in C#
abstract class DataImporter
{
public async Task RunAsync(string path) // template (non virtual)
{
var raw = await File.ReadAllTextAsync(path);
var rows = Parse(raw).Where(Validate).ToList();
Save(rows);
}
protected abstract IEnumerable<Dictionary<string, string>> Parse(string raw);
protected virtual bool Validate(Dictionary<string, string> row) => // hook
row.ContainsKey("email");
protected virtual void Save(List<Dictionary<string, string>> rows) =>
Console.WriteLine($"{rows.Count} rows imported");
}
class JsonImporter : DataImporter
{
protected override IEnumerable<Dictionary<string, string>> Parse(string raw) =>
JsonSerializer.Deserialize<List<Dictionary<string, string>>>(raw)!;
}
Template Method in PHP
abstract class DataImporter
{
final public function run(string $path): void // template method
{
$raw = file_get_contents($path);
$rows = array_filter($this->parse($raw), fn(array $r) => $this->validate($r));
$this->save($rows);
}
abstract protected function parse(string $raw): array;
protected function validate(array $row): bool // hook
{
return !empty($row['email']);
}
protected function save(array $rows): void
{
echo count($rows), ' rows imported', PHP_EOL;
}
}
final class JsonImporter extends DataImporter
{
protected function parse(string $raw): array
{
return json_decode($raw, true, flags: JSON_THROW_ON_ERROR);
}
}
Template Method in Go
// Go has no inheritance: the skeleton receives the variable step through an interface
type Parser interface {
Parse(raw []byte) ([]map[string]string, error)
}
func RunImport(path string, p Parser) error {
raw, err := os.ReadFile(path)
if err != nil {
return err
}
rows, err := p.Parse(raw)
if err != nil {
return err
}
valid := rows[:0]
for _, r := range rows {
if r["email"] != "" {
valid = append(valid, r)
}
}
fmt.Println(len(valid), "rows imported")
return nil
}
type JSONParser struct{}
func (JSONParser) Parse(raw []byte) (rows []map[string]string, err error) {
err = json.Unmarshal(raw, &rows)
return
}
Frequently asked questions
What is the Template Method design pattern?
Define the skeleton of an algorithm in a base class, letting subclasses override certain steps without changing its structure. Write a "template" method (run()) that chains the steps in a fixed order. Variable steps are abstract; optional steps are "hooks" with a default behavior.
When should you use the Template Method pattern?
Algorithms with a fixed structure and variable steps; Frameworks: lifecycles (setUp/tearDown, hooks); Multi-format imports / exports.
What are the pros and cons of the Template Method pattern?
Pros: Eliminates duplication; Step order guaranteed; Clear extension points. Cons: Based on inheritance (rigid); The skeleton can constrain subclasses; Possible Liskov violation if a hook is badly overridden.