00:00

Template Design Pattern in Java

Last updated:

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: private or final methods that every variant must run the same way, such as masking an account number.
  • Primitive operations: abstract methods 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

ComponentResponsibilityIn the Basic Example
Abstract ClassHolds the template method, fixed steps, abstract steps and hooksStatementExporter
Template MethodCalls the steps in a fixed order; usually finalexport()
Concrete ClassesImplement the abstract steps and optionally override hooksCsvStatementExporter, TextStatementExporter
ClientCreates a concrete class and calls the template methodmain

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.

Template Method UML class diagram The Client uses the abstract StatementExporter, whose final export method calls loadTransactions, mask, header, row and footer in order. CsvStatementExporter and TextStatementExporter extend StatementExporter. Client uses «abstract» StatementExporter + export(account) {final} - loadTransactions(account) - mask(account) # header(account) # row(transaction) # footer(transactions) hook export() runs, in order: 1. loadTransactions() 2. mask() 3. header() 4. row() per transaction 5. footer() extends CsvStatementExporter # header(), row() TextStatementExporter # header(), row(), footer()
Template Method: the final export() in the base class fixes the order of steps, and each subclass supplies only the formatting steps.
  1. export() is the template method, marked {final}. The note lists the order it enforces.
  2. loadTransactions() and mask() are private (-), so subclasses cannot change or skip them.
  3. header() and row() are abstract and protected (#): every subclass must implement them.
  4. footer() is a hook with a default; only TextStatementExporter overrides it.

5. Step-by-Step Execution Flow

  1. The client creates a TextStatementExporter and calls export("50100023457788").
  2. The base class runs loadTransactions(), then mask(), producing XXXX7788.
  3. It calls header(maskedAccount); dynamic dispatch runs the text version.
  4. For each transaction it calls row(t), again the text version.
  5. It calls the hook footer(transactions), which the text exporter overrides to print the net movement.
  6. 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.AbstractList implements iteration, indexOf() and more on top of the abstract get() and size(). InputStream.read(byte[], int, int) is built on the abstract single-byte read(). In the Servlet API, HttpServlet.service() dispatches to doGet(), doPost() and the other methods you override.
  • Spring: AbstractApplicationContext.refresh() runs a fixed start-up sequence with protected hooks such as postProcessBeanFactory() and onRefresh(). JdbcTemplate, RestTemplate and TransactionTemplate follow the same idea with callbacks instead of subclasses.

7. Problem Without the Pattern

Two statement exports written as separate copies:

StatementsWithoutTemplate.java
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
    }
}
Console
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.

StatementExportDemo.java
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() is public 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

Console
# 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

  1. Both exports call the same export(), so both show only XXXX7788.
  2. The CSV exporter uses the default empty footer.
  3. The text exporter overrides the footer hook to add the net movement: 85,000 − 28,000 = 57,000.

10. Best Practices and Common Mistakes

Best practices

  • Make the template method final and mandatory steps private.
  • Keep abstract steps few and small; give optional steps hook methods with safe defaults.
  • Name hooks clearly, for example beforeX(), afterX() or requiresX().
  • 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

AspectTemplate MethodStrategyFactory MethodBuilder (with director)
VariesSome steps of an algorithmThe whole algorithmWhich object is createdHow a product is assembled
MechanismInheritanceCompositionInheritanceComposition
ChosenAt compile time, by subclassAt runtime, by injectionAt compile time, by subclassAt runtime, by passing a builder
Controls orderThe base classThe strategy itselfNot applicableThe 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, HttpServlet and 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.