Template Method Pattern
Fix an algorithm sequence in a base class and let subclasses implement selected steps.
· Last updated: 2026-11-05 · 8 min read
Overview
Suppose every report pipeline runs the exact same three steps: trim whitespace, reject empty input, and format the output string. Copy-pasting that sequence into every formatter invites someone to forget the empty-input check in one class or scramble the step order in another, and every new format duplicates the boilerplate again.
Keep trimming and validation in the base class instead. Push only the final formatting step down to subclasses: that is the Template Method pattern, which locks the skeleton of an algorithm into one parent method while letting subclasses fill in the individual steps that vary.
UML
In the UML diagram, ReportTemplate.Run() normalizes and validates the input before invoking Format(). UpperReport and JsonReport override Format() alone; neither touches Run().
History
GoF cataloged Template Method as a behavioral pattern in Design Patterns in 1994. Subclasses vary selected steps while preserving the algorithm structure.1
Why use it?
Because the step order lives in one non-virtual Run() method, subclasses cannot accidentally skip validation or reorder the pipeline, leaving each new format with a single job: implement Format().
Binding steps through inheritance does mean you cannot swap an existing object's formatting rule on the fly at runtime: the exact tradeoff where Strategy parts ways by taking the rule as a plugged-in object or function. Reach for Template Method when locking down the invariant sequence is the main point.
Example
Trim the whitespace on both sides, then produce the report in uppercase format.
using System;
using System.Collections.Generic;
using System.Linq;
ExportResult result = new UpperReport().Run(" hello ");
Console.WriteLine(result.Success + ": " + result.Text);
sealed record ExportResult(bool Success, string Text);
// Keep the shared sequence and validation rules in the base class.
abstract class ReportTemplate
{
public ExportResult Run(string input)
{
string value = input.Trim();
if (value.Length == 0) return new ExportResult(false, "EMPTY_INPUT");
return new ExportResult(true, "REPORT|" + Format(value));
}
protected abstract string Format(string value);
}
// Subclasses change this formatting step rather than the whole workflow.
sealed class UpperReport : ReportTemplate
{
protected override string Format(string value) => value.ToUpperInvariant();
}
sealed class JsonReport : ReportTemplate
{
protected override string Format(string value) => System.Text.Json.JsonSerializer.Serialize(value);
}
True: REPORT|HELLORun() fixes the trim-validate-format cadence once; UpperReport supplies the uppercase conversion, and every sibling subclass inherits the exact same guardrails.
An extended example
This time we use the JSON implementation and pass in an empty input as well. The empty value comes back as a failure result before it reaches Format(). The format changes; the sequence does not.
using System;
using System.Collections.Generic;
using System.Linq;
ReportTemplate report = new JsonReport();
foreach (string input in new[] { " hello ", " " })
{
ExportResult result = report.Run(input);
Console.WriteLine(result.Success + ": " + result.Text);
}
sealed record ExportResult(bool Success, string Text);
// Keep the shared sequence and validation rules in the base class.
abstract class ReportTemplate
{
public ExportResult Run(string input)
{
string value = input.Trim();
if (value.Length == 0) return new ExportResult(false, "EMPTY_INPUT");
return new ExportResult(true, "REPORT|" + Format(value));
}
protected abstract string Format(string value);
}
// Subclasses change this formatting step rather than the whole workflow.
sealed class UpperReport : ReportTemplate
{
protected override string Format(string value) => value.ToUpperInvariant();
}
sealed class JsonReport : ReportTemplate
{
protected override string Format(string value) => System.Text.Json.JsonSerializer.Serialize(value);
}
True: REPORT|"hello"
False: EMPTY_INPUTReturning a success flag alongside the output string lets callers tell an invalid-input failure apart from a rendered report, while the base class guarantees that both formatters enforce the exact same guard. No multi-step sequence to protect? Skip the inheritance hierarchy and use a plain function.
TypeScript example
Here is the same split in TypeScript: the base run() method handles trimming, empty-string rejection, and the REPORT: prefix in one place, delegating only the format-specific step to format().
type ExportResult = { success: true; text: string } | { success: false; code: "EMPTY_INPUT" };
// Keep the shared sequence and validation rules in the base class.
abstract class ReportTemplate {
run(value: string): ExportResult {
const clean = value.trim();
if (clean.length === 0) return { success: false, code: "EMPTY_INPUT" };
return { success: true, text: "REPORT|" + this.format(clean) };
}
protected abstract format(value: string): string;
}
// Subclasses change this formatting step rather than the whole workflow.
class UpperReport extends ReportTemplate {
protected override format(value: string): string { return value.toUpperCase(); }
}
class JsonReport extends ReportTemplate {
protected override format(value: string): string { return JSON.stringify(value); }
}
for (const report of [new UpperReport(), new JsonReport()]) {
const result = report.run(" hello ");
console.log(result.success ? result.text : result.code);
}
const empty = new UpperReport().run(" ");
console.log(empty.success ? empty.text : empty.code);REPORT|HELLO
REPORT|"hello"
EMPTY_INPUTBecause TypeScript has no final keyword matching C#'s non-virtual method, subclasses simply implement format() and leave run() untouched, while empty strings still fail before reaching the formatter (note that ASCII inputs behave identically across both runtimes, whereas Unicode whitespace and casing rules can differ).
Compose functions and LINQ instead of inheritance
When the only varying piece is a single string-to-string function, passing a delegate or lambda directly into Run is much lighter than minting subclasses. Run still enforces the trim-and-validate sequence, LINQ's Select maps it across a batch, and an entire subclass collapses into a one-line function argument.
C#
using System;
using System.Linq;
using System.Text.Json;
ExportResult Run(string input, Func<string, string> format)
{
string value = input.Trim();
if (value.Length == 0) return new ExportResult(false, "EMPTY_INPUT");
return new ExportResult(true, "REPORT|" + format(value));
}
var inputs = new[] { " hello ", " " };
// Supply only the format; invalid input fails before the transformation is called.
var results = inputs.Select(input => Run(input, value => JsonSerializer.Serialize(value)))
.ToArray();
foreach (ExportResult result in results) Console.WriteLine(result.Text);
sealed record ExportResult(bool Success, string Text);TypeScript
type ExportResult = { success: true; text: string } | { success: false; code: "EMPTY_INPUT" };
function run(input: string, format: (value: string) => string): ExportResult {
const value = input.trim();
if (value.length === 0) return { success: false, code: "EMPTY_INPUT" };
return { success: true, text: "REPORT|" + format(value) };
}
const inputs = [" hello ", " "];
// Keep the shared workflow in one function and apply it to every input.
const results = inputs.map(input => run(input, value => JSON.stringify(value)));
for (const result of results) console.log(result.success ? result.text : result.code);REPORT|"hello"
EMPTY_INPUTInheritance-based Template Method couples subclasses tightly to the parent class's control flow and protected members; once hooks and subclasses multiply, passing functions or Strategy objects keeps the exact same trim → validate → transform pipeline without the class-hierarchy weight.
Microsoft: Introduction to LINQ queries
Related reading
Footnotes
- Gamma, Helm, Johnson, Vlissides. Design Patterns (1994). Publisher record. Behavioral patterns, Template Method. ↩