Template Method
Defines the skeleton of an algorithm in a base class, deferring some steps to subclasses.
Context
You have several algorithms with the same structure but distinct specific steps (parsing, validating, exporting).
Problem
You duplicate the algorithm's skeleton in each implementation.
Solution
The base class defines the Run() method with the sequence and calls abstract hooks that subclasses fill in.
#Example in C#
public abstract class ReportGenerator
{
public string Generate() // template
{
var data = LoadData();
var processed = Process(data);
return Format(processed);
}
protected abstract IEnumerable<Row> LoadData();
protected virtual IEnumerable<Row> Process(IEnumerable<Row> rows) => rows; // hook
protected abstract string Format(IEnumerable<Row> rows);
}
public class CsvReport : ReportGenerator
{
protected override IEnumerable<Row> LoadData() => /* from DB */;
protected override string Format(IEnumerable<Row> rows) => /* CSV */;
}When NOT to use it
If the steps are very different per implementation: prefer Strategy (composition over inheritance).
Tradeoffs
| Pro | Con |
|---|---|
| Reuses the skeleton | Couples by inheritance (rigid) |
#behavioral #gof #inheritance