Menu
Coddy logo textTech

Template Method Pattern

Part of the Object Oriented Programming section of Coddy's Java journey — lesson 73 of 87.

The Template Method Pattern is a behavioral design pattern that defines the skeleton of an algorithm in a base class, allowing subclasses to override specific steps without changing the overall structure. Think of it like a recipe: the general cooking process stays the same, but individual ingredients or techniques can vary.

The pattern uses an abstract class with a template method that calls a sequence of steps. Some steps have default implementations, while others are abstract and must be implemented by subclasses:

abstract class DataProcessor {
    // Template method - defines the algorithm structure
    public final void process() {
        readData();
        processData();
        saveData();
    }
    
    abstract void readData();
    abstract void processData();
    
    // Default implementation (hook method)
    void saveData() {
        System.out.println("Saving to default location");
    }
}

class CSVProcessor extends DataProcessor {
    void readData() {
        System.out.println("Reading CSV file");
    }
    
    void processData() {
        System.out.println("Parsing CSV data");
    }
}

class XMLProcessor extends DataProcessor {
    void readData() {
        System.out.println("Reading XML file");
    }
    
    void processData() {
        System.out.println("Parsing XML data");
    }
}

The template method is typically marked final to prevent subclasses from altering the algorithm's structure. When called, it executes the same sequence for all subclasses:

DataProcessor csv = new CSVProcessor();
csv.process();
// Output:
// Reading CSV file
// Parsing CSV data
// Saving to default location

The Template Method Pattern is ideal when you have algorithms that share the same structure but differ in specific steps. It promotes code reuse by placing common logic in the base class while allowing customization through inheritance.

challenge icon

Challenge

Easy

Let's build a document generation system using the Template Method Pattern! You'll create a framework where different document types (reports and invoices) follow the same generation process but customize specific steps. This is perfect for scenarios where the overall workflow is fixed, but the details vary by document type.

You'll organize your code across four files:

  • DocumentGenerator.java: Create the abstract base class that defines the template method. Your DocumentGenerator should have:

    A final method called generateDocument() that defines the algorithm skeleton by calling three steps in order: createHeader(), createBody(), and createFooter().

    Two abstract methods: createHeader() and createBody() that subclasses must implement.

    A hook method createFooter() with a default implementation that prints --- End of Document ---.

  • ReportGenerator.java: Create a concrete subclass for generating reports. It should take a report title (String) through its constructor.

    The createHeader() method prints === REPORT: [title] ===

    The createBody() method prints Report content goes here...

    Use the inherited default footer.

  • InvoiceGenerator.java: Create another concrete subclass for generating invoices. It should take a customer name (String) and an amount (double) through its constructor.

    The createHeader() method prints *** INVOICE ***

    The createBody() method prints Customer: [name] on one line, then Amount Due: $[amount] on the next line (format amount to two decimal places).

    Override createFooter() to print Thank you for your business!

  • Main.java: Bring your template method system together! You'll receive three inputs: a report title (String), a customer name (String), and an invoice amount (double).

    Create a ReportGenerator with the title and call generateDocument(). Print an empty line for separation. Then create an InvoiceGenerator with the customer name and amount, and call generateDocument().

You will receive three inputs in order: report title (String), customer name (String), and invoice amount (double).

For example, with inputs Q4 Sales, Acme Corp, and 1500.00, your output would be:

=== REPORT: Q4 Sales ===
Report content goes here...
--- End of Document ---

*** INVOICE ***
Customer: Acme Corp
Amount Due: $1500.00
Thank you for your business!

Notice how both document types follow the same three-step process defined in the template method, but each customizes the steps differently. The ReportGenerator uses the default footer while InvoiceGenerator provides its own—this is the power of hook methods in the Template Method Pattern!

Cheat sheet

The Template Method Pattern is a behavioral design pattern that defines the skeleton of an algorithm in a base class, allowing subclasses to override specific steps without changing the overall structure.

The pattern uses an abstract class with a template method that calls a sequence of steps. Some steps have default implementations, while others are abstract and must be implemented by subclasses:

abstract class DataProcessor {
    // Template method - defines the algorithm structure
    public final void process() {
        readData();
        processData();
        saveData();
    }
    
    abstract void readData();
    abstract void processData();
    
    // Default implementation (hook method)
    void saveData() {
        System.out.println("Saving to default location");
    }
}

Concrete subclasses implement the abstract methods:

class CSVProcessor extends DataProcessor {
    void readData() {
        System.out.println("Reading CSV file");
    }
    
    void processData() {
        System.out.println("Parsing CSV data");
    }
}

The template method is marked final to prevent subclasses from altering the algorithm's structure. When called, it executes the same sequence for all subclasses:

DataProcessor csv = new CSVProcessor();
csv.process();
// Output:
// Reading CSV file
// Parsing CSV data
// Saving to default location

Key characteristics:

  • Template method is final and defines the algorithm structure
  • Abstract methods must be implemented by subclasses
  • Hook methods provide default implementations that can be optionally overridden
  • Promotes code reuse by placing common logic in the base class

Try it yourself

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Read inputs
        String reportTitle = scanner.nextLine();
        String customerName = scanner.nextLine();
        double invoiceAmount = scanner.nextDouble();
        
        // TODO: Create a ReportGenerator with the title and call generateDocument()
        
        // TODO: Print an empty line for separation
        
        // TODO: Create an InvoiceGenerator with customer name and amount, and call generateDocument()
        
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming