Template Design Pattern in Java
The template design pattern in Java, usually called the Template Method pattern, defines the fixed outline of an algorithm in one base-class method and lets subclasses fill in only the steps that vary. The base class decides what happens and in which order; subclasses decide how particular steps are done.
It matters because similar processes are often copied and then drift apart. A CSV statement export and a text statement export share loading, masking and formatting steps; when one copy forgets to mask the account number, private data leaks. A template method keeps the shared steps in one place. It is a behavioral design pattern, and parts of the JDK and Spring are built on it.
1. What Is the Template Design Pattern?
The GoF intent is: "Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure."
An abstract class contains one public method, the template method, that calls a sequence of other methods. Those methods come in three kinds:
- Fixed steps:
privateorfinalmethods that every variant must run the same way, such as masking an account number. - Primitive operations:
abstractmethods that each subclass must implement, such as formatting a row. - Hooks: methods with a default implementation, often empty, that subclasses may override, such as an optional footer.
The template method itself is usually final, so no subclass can change the order of steps or skip a mandatory one. Control flows from the base class into the subclass, not the other way round, which is known as the Hollywood Principle: "don't call us, we'll call you". The pattern uses inheritance to remove duplication while keeping the algorithm's structure under the base class's control.
2. Key Components
| Component | Responsibility | In the Basic Example |
|---|---|---|
| Abstract Class | Holds the template method, fixed steps, abstract steps and hooks | StatementExporter |
| Template Method | Calls the steps in a fixed order; usually final | export() |
| Concrete Classes | Implement the abstract steps and optionally override hooks | CsvStatementExporter, TextStatementExporter |
| Client | Creates a concrete class and calls the template method | main |
The client calls the template method on a concrete object. The base class runs its fixed steps and, at the right moments, calls the subclass's versions of the abstract steps and hooks.
3. When Is Template Method Useful?
- Exports and reports: several output formats that share loading, masking and totalling.
- Checkout flows: card, UPI and wallet payments that share validation and auditing but authorise differently.
- Batch imports: jobs that all read, validate and write in chunks, but parse different file formats.
4. UML Class Diagram
The diagram shows the Basic Example. Italic members are abstract.
export() in the base class fixes the order of steps, and each subclass supplies only the formatting steps.export()is the template method, marked{final}. The note lists the order it enforces.loadTransactions()andmask()are private (-), so subclasses cannot change or skip them.header()androw()are abstract and protected (#): every subclass must implement them.footer()is a hook with a default; onlyTextStatementExporteroverrides it.
5. Step-by-Step Execution Flow
- The client creates a
TextStatementExporterand callsexport("50100023457788"). - The base class runs
loadTransactions(), thenmask(), producingXXXX7788. - It calls
header(maskedAccount); dynamic dispatch runs the text version. - For each transaction it calls
row(t), again the text version. - It calls the hook
footer(transactions), which the text exporter overrides to print the net movement. - The base class joins the pieces and returns the finished statement to the client.
6. Real-World Use Cases
- E-commerce: order-confirmation documents and marketplace feeds in several formats.
- Payments and banking: payment flows per method sharing validation and audit, and statement generation per channel.
- Notifications: a send pipeline (load template, personalise, check opt-out, deliver) where only delivery differs per channel.
- The JDK:
java.util.AbstractListimplements iteration,indexOf()and more on top of the abstractget()andsize().InputStream.read(byte[], int, int)is built on the abstract single-byteread(). In the Servlet API,HttpServlet.service()dispatches todoGet(),doPost()and the other methods you override. - Spring:
AbstractApplicationContext.refresh()runs a fixed start-up sequence with protected hooks such aspostProcessBeanFactory()andonRefresh().JdbcTemplate,RestTemplateandTransactionTemplatefollow the same idea with callbacks instead of subclasses.
7. Problem Without the Pattern
Two statement exports written as separate copies:
import java.util.List;
public class StatementsWithoutTemplate {
record Transaction(String date, String description, long amountInRupees) { }
static List<Transaction> load(String account) {
return List.of(new Transaction("2026-10-03", "Salary", 85_000), new Transaction("2026-10-07", "Rent", -28_000));
}
// CSV export: load, mask, header, rows
static String csvStatement(String account) {
StringBuilder out = new StringBuilder("account,date,description,amount\n");
String masked = "XXXX" + account.substring(account.length() - 4);
for (Transaction t : load(account)) {
out.append(masked).append(',').append(t.date()).append(',').append(t.description()).append(',').append(t.amountInRupees()).append('\n');
}
return out.toString();
}
// Text export: the same steps copied, and the masking step was forgotten
static String textStatement(String account) {
StringBuilder out = new StringBuilder("Statement for " + account + "\n");
for (Transaction t : load(account)) {
out.append(t.date()).append(" ").append(t.description()).append(" ").append(t.amountInRupees()).append('\n');
}
return out.toString();
}
public static void main(String[] args) {
System.out.print(csvStatement("50100023457788"));
System.out.print(textStatement("50100023457788")); // full account number leaked
}
}
account,date,description,amount
XXXX7788,2026-10-03,Salary,85000
XXXX7788,2026-10-07,Rent,-28000
Statement for 50100023457788
2026-10-03 Salary 85000
2026-10-07 Rent -28000
- Duplication: loading and looping are written twice.
- A real defect: the text version forgot masking and prints the full account number.
- No enforced order: nothing guarantees that every format runs every mandatory step.
- Costly change: a new mandatory step, such as a watermark, must be added to each copy.
8. Solution Using the Pattern
Move the shared outline into a final export() method in an abstract StatementExporter. Loading and masking become private steps that run for every format. Each format implements only header() and row(), and may override the footer() hook.
The leak cannot happen again, because no subclass can bypass mask(). Each format class now contains only formatting, and a new mandatory step is added once, in the base class. A PDF or JSON exporter is one new subclass.
9. Template Design Pattern in Java: Code Examples
Each example is a single file that runs on Java 21 with java FileName.java.
Basic Example: Bank Statement Exports
Problem: fix section 7 so that every format loads and masks in the same way, with only formatting differing.
import java.util.List;
public class StatementExportDemo {
record Transaction(String date, String description, long amountInRupees) { }
// Abstract class with the template method
abstract static class StatementExporter {
// Template method: the steps and their order are fixed here, once
public final String export(String accountNumber) {
List<Transaction> transactions = loadTransactions(accountNumber);
String maskedAccount = mask(accountNumber); // mandatory for every format
StringBuilder out = new StringBuilder(header(maskedAccount));
for (Transaction t : transactions) {
out.append(row(t));
}
out.append(footer(transactions));
return out.toString();
}
// Fixed steps: subclasses cannot change them
private List<Transaction> loadTransactions(String account) {
return List.of(new Transaction("2026-10-03", "Salary", 85_000), new Transaction("2026-10-07", "Rent", -28_000));
}
private String mask(String account) {
return "XXXX" + account.substring(account.length() - 4);
}
// Steps every format must supply
protected abstract String header(String maskedAccount);
protected abstract String row(Transaction t);
// Hook: optional, with a sensible default
protected String footer(List<Transaction> transactions) {
return "";
}
}
static final class CsvStatementExporter extends StatementExporter {
protected String header(String account) { return "# account " + account + "\ndate,description,amount\n"; }
protected String row(Transaction t) { return t.date() + "," + t.description() + "," + t.amountInRupees() + "\n"; }
}
static final class TextStatementExporter extends StatementExporter {
protected String header(String account) { return "Statement for " + account + "\n"; }
protected String row(Transaction t) { return String.format("%s %-8s %8d\n", t.date(), t.description(), t.amountInRupees()); }
@Override
protected String footer(List<Transaction> transactions) { // this format uses the hook
long net = transactions.stream().mapToLong(Transaction::amountInRupees).sum();
return "Net movement: " + net + "\n";
}
}
public static void main(String[] args) {
String account = "50100023457788";
System.out.print(new CsvStatementExporter().export(account));
System.out.print(new TextStatementExporter().export(account));
}
}
Important classes and methods
export()ispublic final: callers use it, subclasses cannot override it.- The fixed steps are
private, so they are not even visible to subclasses. - The abstract steps are
protected: subclasses implement them, but outside code cannot call them out of order.
Expected output
# account XXXX7788
date,description,amount
2026-10-03,Salary,85000
2026-10-07,Rent,-28000
Statement for XXXX7788
2026-10-03 Salary 85000
2026-10-07 Rent -28000
Net movement: 57000
How it runs
- Both exports call the same
export(), so both show onlyXXXX7788. - The CSV exporter uses the default empty footer.
- The text exporter overrides the footer hook to add the net movement: 85,000 − 28,000 = 57,000.
Practical Example: Checkout Flow per Payment Method
Problem: card, UPI and wallet payments must all validate the order and write an audit entry before and after, but they authorise differently, only some need an OTP, and only the wallet gives cashback.
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
public class PaymentFlowTemplateDemo {
record Order(String id, BigDecimal amount) { }
abstract static class PaymentFlow {
private final List<String> auditLog;
protected PaymentFlow(List<String> auditLog) { this.auditLog = auditLog; }
// Template method
public final String pay(Order order) {
audit(order, "started");
try {
validate(order);
if (requiresOtp(order)) { // hook decides whether this step runs
verifyOtp(order);
}
String reference = authorize(order);
afterSuccess(order, reference); // hook with an empty default
return order.id() + " paid via " + method() + ": " + reference;
} catch (IllegalStateException e) {
return order.id() + " failed via " + method() + ": " + e.getMessage();
} finally {
audit(order, "finished"); // always runs, whatever the subclass does
}
}
// Fixed, shared steps
private void validate(Order order) {
if (order.amount().signum() <= 0) throw new IllegalStateException("amount must be positive");
}
private void verifyOtp(Order order) {
System.out.println(" [" + method() + "] OTP verified for " + order.id());
}
private void audit(Order order, String event) {
auditLog.add(method() + " " + order.id() + " " + event);
}
// Primitive operations: every method must supply them
protected abstract String method();
protected abstract String authorize(Order order);
// Hooks: optional overrides
protected boolean requiresOtp(Order order) { return false; }
protected void afterSuccess(Order order, String reference) { }
}
static final class CardFlow extends PaymentFlow {
CardFlow(List<String> log) { super(log); }
protected String method() { return "card"; }
protected boolean requiresOtp(Order order) { return order.amount().compareTo(new BigDecimal("5000")) > 0; }
protected String authorize(Order order) { return "CARD-AUTH-" + order.id(); }
}
static final class UpiFlow extends PaymentFlow {
UpiFlow(List<String> log) { super(log); }
protected String method() { return "upi"; }
protected String authorize(Order order) {
if (order.amount().compareTo(new BigDecimal("100000")) > 0) throw new IllegalStateException("UPI limit exceeded");
return "UPI-" + order.id();
}
}
static final class WalletFlow extends PaymentFlow {
WalletFlow(List<String> log) { super(log); }
protected String method() { return "wallet"; }
protected String authorize(Order order) { return "WAL-" + order.id(); }
protected void afterSuccess(Order order, String reference) {
System.out.println(" [wallet] cashback credited for " + order.id());
}
}
public static void main(String[] args) {
List<String> audit = new ArrayList<>();
System.out.println(new CardFlow(audit).pay(new Order("ORD-1", new BigDecimal("2499"))));
System.out.println(new CardFlow(audit).pay(new Order("ORD-2", new BigDecimal("12999"))));
System.out.println(new UpiFlow(audit).pay(new Order("ORD-3", new BigDecimal("150000"))));
System.out.println(new WalletFlow(audit).pay(new Order("ORD-4", new BigDecimal("399"))));
System.out.println("Audit entries: " + audit.size() + ", last: " + audit.get(audit.size() - 1));
}
}
Important classes and methods
pay()wraps the steps intry/finally, so the "finished" audit entry is written even when a subclass's step throws.requiresOtp()is a hook that controls the flow: the card flow returnstrueabove Rs. 5,000.afterSuccess()is an empty hook that only the wallet overrides.
Expected output
ORD-1 paid via card: CARD-AUTH-ORD-1
[card] OTP verified for ORD-2
ORD-2 paid via card: CARD-AUTH-ORD-2
ORD-3 failed via upi: UPI limit exceeded
[wallet] cashback credited for ORD-4
ORD-4 paid via wallet: WAL-ORD-4
Audit entries: 8, last: wallet ORD-4 finished
How it runs
- The Rs. 2,499 card payment skips OTP; the Rs. 12,999 one requires it.
- The UPI payment fails inside
authorize(), and the template turns that into a "failed" result. - Four payments produce eight audit entries, a "started" and a "finished" each, including for the failed one.
Real-World Enterprise Example: Generic Batch Import Job
Problem: several nightly imports share the same mechanics: parse each line, validate it, skip bad lines up to a limit, and write good records in chunks to reduce database round-trips. Only parsing, validation rules and the write target differ.
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class BatchImportTemplateDemo {
record ImportReport(String job, int read, int written, int skipped, List<String> errors, int chunks) { }
// Generic template for "read, validate, write in chunks, with a skip limit"
abstract static class ImportJob<T> {
private final int chunkSize;
private final int skipLimit;
protected ImportJob(int chunkSize, int skipLimit) {
this.chunkSize = chunkSize;
this.skipLimit = skipLimit;
}
public final ImportReport run(List<String> lines) {
List<T> chunk = new ArrayList<>();
List<String> errors = new ArrayList<>();
int written = 0;
int chunks = 0;
for (int i = 0; i < lines.size(); i++) {
String line = lines.get(i);
try {
T item = parse(line);
Optional<String> problem = validate(item);
if (problem.isPresent()) throw new IllegalArgumentException(problem.get());
chunk.add(item);
} catch (IllegalArgumentException e) {
errors.add("line " + (i + 1) + ": " + e.getMessage());
if (errors.size() > skipLimit) {
throw new IllegalStateException(name() + " aborted: more than " + skipLimit + " bad lines");
}
}
if (chunk.size() == chunkSize) {
written += flush(chunk);
chunks++;
}
}
if (!chunk.isEmpty()) {
written += flush(chunk);
chunks++;
}
return new ImportReport(name(), lines.size(), written, errors.size(), List.copyOf(errors), chunks);
}
private int flush(List<T> chunk) {
writeChunk(List.copyOf(chunk)); // one database round-trip per chunk
int size = chunk.size();
chunk.clear();
return size;
}
protected abstract String name();
protected abstract T parse(String line);
protected abstract void writeChunk(List<T> items);
protected Optional<String> validate(T item) { return Optional.empty(); } // hook
}
// Concrete job 1
record Product(String sku, String title, long priceInPaise) { }
static final class ProductImportJob extends ImportJob<Product> {
ProductImportJob() { super(2, 3); }
protected String name() { return "product-import"; }
protected Product parse(String line) {
String[] f = line.split(",");
if (f.length != 3) throw new IllegalArgumentException("expected 3 fields, got " + f.length);
try {
return new Product(f[0].trim(), f[1].trim(), new BigDecimal(f[2].trim()).movePointRight(2).longValueExact());
} catch (NumberFormatException | ArithmeticException e) {
throw new IllegalArgumentException("bad price '" + f[2].trim() + "'");
}
}
protected Optional<String> validate(Product p) {
return p.priceInPaise() <= 0 ? Optional.of("price must be positive for " + p.sku()) : Optional.empty();
}
protected void writeChunk(List<Product> items) {
System.out.println(" [db] upsert products " + items.stream().map(Product::sku).toList());
}
}
// Concrete job 2
record Customer(String id, String email) { }
static final class CustomerImportJob extends ImportJob<Customer> {
CustomerImportJob() { super(3, 0); }
protected String name() { return "customer-import"; }
protected Customer parse(String line) {
String[] f = line.split(";");
return new Customer(f[0].trim(), f.length > 1 ? f[1].trim() : "");
}
protected Optional<String> validate(Customer c) {
return c.email().contains("@") ? Optional.empty() : Optional.of("invalid email for " + c.id());
}
protected void writeChunk(List<Customer> items) {
System.out.println(" [db] insert customers " + items.stream().map(Customer::id).toList());
}
}
public static void main(String[] args) {
System.out.println(new ProductImportJob().run(List.of(
"SKU-1, Wireless mouse, 799.00",
"SKU-2, USB-C hub, abc",
"SKU-3, Laptop stand, 1499.50",
"SKU-4, Keyboard",
"SKU-5, Webcam, 2299.00")));
try {
new CustomerImportJob().run(List.of("C-1; asha@example.com", "C-2; not-an-email", "C-3; ravi@example.com"));
} catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
}
}
Important classes and methods
ImportJob<T>is a generic abstract class;run()holds chunking, the skip policy and reporting.- Subclasses implement
parse()andwriteChunk(), and may override thevalidate()hook. - Prices are parsed with
BigDecimaland stored in paise, which avoids floating-point rounding errors. - Each run keeps its state in local variables, so one job object can safely run on several threads at once.
Expected output
[db] upsert products [SKU-1, SKU-3]
[db] upsert products [SKU-5]
ImportReport[job=product-import, read=5, written=3, skipped=2, errors=[line 2: bad price 'abc', line 4: expected 3 fields, got 2], chunks=2]
customer-import aborted: more than 0 bad lines
How it runs
- The product job skips two bad lines (allowed: three) and writes three products in two chunks.
- The customer job allows no bad lines, so the invalid email aborts the run before anything is written.
- This read-process-write shape is the same one Spring Batch provides for large production jobs.
10. Best Practices and Common Mistakes
Best practices
- Make the template method
finaland mandatory stepsprivate. - Keep abstract steps few and small; give optional steps hook methods with safe defaults.
- Name hooks clearly, for example
beforeX(),afterX()orrequiresX(). - Thread safety: keep per-run state in local variables, not fields, so one instance can serve many threads.
Common mistakes
- Overridable template methods, which let a subclass skip mandatory steps.
- Calling the template method from a constructor, before subclass fields are set.
- Too many hooks and boolean flags, which make the outline impossible to follow.
- Overengineering: an abstract class for two methods that share one line.
11. When to Use and When Not to Use
Use it when the overall sequence is stable and must be enforced, the variations are confined to a few steps, and you control the class hierarchy.
Avoid it when variants differ in their overall flow rather than in a few steps, when steps must be mixed and matched at runtime, which suits Strategy better, or when your classes already need a different superclass, because Java allows only one.
12. Advantages and Disadvantages
Advantages
- No duplicated workflow: shared steps live once.
- Enforced order and mandatory steps.
- Small subclasses focused on what differs.
- Natural extension points through hooks.
Disadvantages
- Inheritance coupling: subclasses depend on the base class's internals.
- Fixed at compile time: behaviour cannot be swapped at runtime.
- Harder to read when the flow jumps between base and subclass.
13. Comparison with Similar Patterns
| Aspect | Template Method | Strategy | Factory Method | Builder (with director) |
|---|---|---|---|---|
| Varies | Some steps of an algorithm | The whole algorithm | Which object is created | How a product is assembled |
| Mechanism | Inheritance | Composition | Inheritance | Composition |
| Chosen | At compile time, by subclass | At runtime, by injection | At compile time, by subclass | At runtime, by passing a builder |
| Controls order | The base class | The strategy itself | Not applicable | The director |
Choose Template Method when the outline is fixed and only some steps vary. Choose Strategy when the whole behaviour should be swappable at runtime. A Factory Method is often one step inside a template method, as in the Factory tutorial's order export job. The Command pattern packages requests instead of structuring algorithms.
14. Summary
- The template design pattern in Java fixes an algorithm's outline in a base-class method and lets subclasses fill in some steps.
- Purpose: remove duplicated workflows and enforce mandatory steps and order.
- Components: Abstract Class with a template method, Concrete Classes, Client.
- Steps are fixed (private), required (abstract) or optional (hooks).
- Used in exports, payment flows, batch jobs,
AbstractList,HttpServletand Spring's context start-up. - Benefits: less duplication, enforced structure and small subclasses.
- Keep the template method final, avoid calling it from constructors, and prefer Strategy when behaviour must change at runtime.
15. Java Design Pattern Interview Questions and Answers
Q1. Why should the template method usually be final?
The whole point is that the base class controls the order and the mandatory steps. If subclasses can override the template method, one of them can reorder the steps or skip a security step such as masking, which defeats the pattern. Making it final turns that into a compile error.
Q2. What is the Hollywood Principle, and how does Template Method follow it?
"Don't call us, we'll call you": high-level code calls low-level code at the right time, not the reverse. In Template Method, the base class calls the subclass's steps; subclasses never call the template method's internals to drive the flow. Frameworks use the same principle, which is why it is also called inversion of control.
Q3. How do Spring's JdbcTemplate and TransactionTemplate relate to this pattern?
They keep the fixed outline (open the connection, run your code, handle exceptions, close or commit) but take the varying step as a callback object or lambda instead of a subclass. This composition-based form avoids inheritance and lets you vary the step per call.
Long total = transactionTemplate.execute(status ->
jdbcTemplate.queryForObject("SELECT SUM(amount) FROM payments", Long.class));Q4. A base class calls its template method from its constructor, and subclasses see null fields. Why?
Java runs the superclass constructor before the subclass's field initialisers and constructor body. When the base constructor calls an overridden step, the subclass method runs while its fields are still null or zero. Never call overridable methods from a constructor; call the template method after construction instead.
Q5. Your base class now has eight hooks and three boolean flags. What would you do?
That usually means the variants differ in structure, not just in steps. Split the base class into smaller templates for each real family of flows, or move the varying behaviour into strategy objects that are composed into one class. Fewer, well-named extension points are easier to understand and test.