Video in progress
What is the Template Method pattern? Show it with a simple example.
In Template Method, the skeleton of an algorithm is written in a final method of the parent class, and some steps are abstract for the subclasses to fill in. The sequence stays fixed, only certain steps change.
📖 Answer
A report export example: fetching the data and writing to a file always happen in the same order, only the format differs.
public abstract class ReportExporter {
public final byte[] export(LocalDate from, LocalDate to) {
List<Row> rows = load(from, to); // common
byte[] body = render(rows); // each format does its own
audit(rows.size()); // common
return body;
}
protected abstract byte[] render(List<Row> rows);
protected List<Row> load(LocalDate from, LocalDate to) { /* SQL */ return List.of(); }
private void audit(int count) { /* log */ }
}
class CsvExporter extends ReportExporter {
protected byte[] render(List<Row> rows) { /* CSV */ return new byte[0]; }
}
export is final, so a subclass can't break the sequence. load is a "hook": a subclass can override it if it wants.
AbstractList in the JDK works like this: you only write get and size, and iterator, contains and indexOf come for free. Spring's JdbcTemplate, as the name suggests, is close to this idea too.
Sign up to mark studied questions and save your progress.