Knowledge Guide
HomeOO & Low-Level DesignBehavioral

Template Method Pattern

The template method is a behavioral design pattern that defines the skeleton of an algorithm in the superclass but allows subclasses to change specific steps without changing the algorithm's structure. Put differently, it acts as an algorithm's template, letting subclasses take over specific steps while maintaining its general structure.

The pattern adheres to the "Don't call us, we'll call you" principle, in which the subclasses are assigned specific tasks by the superclass, which contains the fixed steps of the algorithm.

Consider creating a program that can provide reports in several formats, including CSV, HTML, and PDF. The procedures for gathering data, processing data, and producing reports are the same for all report types. The details of every step, however, differ based on the kind of report. Implementing each report type independently results in code redundancy, particularly in processes that are shared by all report kinds.

Template Method Pattern - Report Generator
Template Method Pattern - Report Generator

The Template Method design handles this by encapsulating the algorithm's skeleton in a method and delegating some steps to subclasses. The image above illustrates that an abstract base class ReportGenerator with a template function generateReport() can be created. The report creation process is defined by this method; however, the subclasses are responsible for carrying out specific tasks such as data collecting, processing, and formatting.

This way, the common structure of the report generation process is defined in the base class while allowing flexibility in implementing each step. The result is a more organized and less redundant codebase, where common functionalities are centralized, and subclasses handle specific details.

Real-World Example

A real-world example of the Template Method pattern can be found in the process of making different types of beverages, such as coffee and tea. The overall process of preparing a hot beverage involves common steps like boiling water, brewing, and serving. However, the specific steps for brewing and serving differ between coffee and tea.

In this scenario:

The illustration below shows two parts, one for coffee and one for tea. The steps which are common for both are shown in the center line and those that vary for the two beverages are shown in their specific parts.

Template Method Pattern - Real-World Example
Template Method Pattern - Real-World Example

Structure of Template Method

The Template Method pattern involves the following key participants:

  1. Abstract Class (or Interface): This is the class that defines the template method, which is the skeleton of the algorithm. The template method consists of a series of steps, some of which may be implemented in the abstract class, while others are left to be implemented by concrete subclasses. It serves as a blueprint for the algorithm.
  2. Concrete Class (or Subclass): These are the classes that extend the abstract class and provide concrete implementations for the steps left open in the template method. Each concrete class represents a specific variation of the algorithm and customizes the behavior according to its requirements.
Template Method Pattern - Class Diagram
Template Method Pattern - Class Diagram

The interaction between these participants allows for the creation of a family of algorithms sharing a common structure, where subclasses can customize specific steps without altering the overall algorithmic framework. This promotes code reuse, encapsulation, and flexibility in adapting the algorithm to different scenarios.

Implementation of Template Method

Consider a program for generating different types of reports, such as CSV, HTML, and PDF. Each report follows a similar process but requires different implementations for certain steps.

Abstract Class ReportGenerator { Method generateReport() { data = collectData() processedData = processData(data) report = formatReport(processedData) printReport(report) } Abstract Method collectData() Abstract Method processData(data) Abstract Method formatReport(processedData) Method printReport(report) { // Common implementation for printing the report } } Class CSVReportGenerator extends ReportGenerator { Method collectData() { // Implementation for collecting CSV data } Method processData(data) { // Implementation for processing CSV data } Method formatReport(processedData) { // Implementation for formatting CSV report } } Class HTMLReportGenerator extends ReportGenerator { // Implement collectData, processData, and formatReport specifically for HTML } Class PDFReportGenerator extends ReportGenerator { // Implement collectData, processData, and formatReport specifically for PDF } // Client Code Main { csvReportGenerator = new CSVReportGenerator() csvReportGenerator.generateReport() htmlReportGenerator = new HTMLReportGenerator() htmlReportGenerator.generateReport() pdfReportGenerator = new PDFReportGenerator() pdfReportGenerator.generateReport() }

This structure allows for defining the common steps of report generation in the base class while enabling subclasses to implement specific behavior for different report types. It reduces redundancy and allows for extending the system with new report types easily.

Implementation

java
public abstract class ReportGenerator {

  protected abstract String collectData();

  protected abstract String processData(String data);

  protected abstract String formatReport(String processedData);

  private void printReport(String report) {
    System.out.println(report);
  }

  public void generateReport() {
    String data = collectData();
    String processedData = processData(data);
    String report = formatReport(processedData);
    printReport(report);
  }
}

class CSVReportGenerator extends ReportGenerator {

  protected String collectData() {
    return "CSV Data";
  }

  protected String processData(String data) {
    return "Processed " + data;
  }

  protected String formatReport(String processedData) {
    return "CSV Report: " + processedData;
  }
}

// Similar classes for HTMLReportGenerator and PDFReportGenerator

public class Solution {

  public static void main(String[] args) {
    ReportGenerator csvReport = new CSVReportGenerator();
    csvReport.generateReport();
    // Similarly for other report types
  }
}

Application of Template Method

Some notable applications include:

1. Software Frameworks:

Graphical User Interface (GUI) Frameworks: Template Method is often employed in GUI frameworks where the overall structure of handling user inputs and events is predefined, but the specific behavior may vary in different applications or components.

Web Frameworks: Web frameworks utilize Template Method to provide a structured approach for handling HTTP requests and responses. The overall request lifecycle remains consistent, but developers can customize specific steps based on application requirements.

2. Algorithm Design:

Sorting Algorithms: Template Method can be applied to sorting algorithms. The overall sorting process remains the same, but specific steps like element comparison or swapping may vary depending on the sorting algorithm (e.g., quicksort, mergesort).

Search Algorithms: Similar to sorting, search algorithms can benefit from the Template Method pattern. The search process structure remains consistent, while specific steps like comparing elements may differ.

3. Game Development:

Game Design Frameworks: In game development, the Template Method pattern can be employed in frameworks that define the overall game loop structure. While the main loop remains constant, specific behaviors for updating game objects or handling user input can be customized by individual games.

Character Animation: When designing character animation systems, a common structure for updating and rendering characters can be defined using the Template Method. The specifics of animation sequences can vary for different characters.

4. Educational Software:

Learning Management Systems: Educational software often involves structured processes for presenting content, quizzes, and assessments. A Template Method can define the overall flow, while individual courses or modules provide specific implementations for content delivery and assessments.

5. Document Generation:

Report Generation: In applications generating reports or documents, a Template Method can define the structure of document creation. Specific steps for adding headers, footers, and content generation can be customized based on the type of document.

6. Business Process Automation:

Workflow Management Systems: Systems that automate business processes can benefit from the Template Method pattern. The overall workflow structure remains consistent, but specific steps for handling tasks, approvals, or notifications can be tailored to different business processes.

Pros and Cons

ProsCons
Code Reuse: The Template Method pattern promotes code reuse by providing a common structure for algorithms. The overall algorithm is defined in the template method, and individual steps can be reused in subclasses.Reduced Runtime Flexibility: The pattern determines the overall algorithm structure during compile-time, limiting the runtime flexibility of the algorithm. Dynamic changes to the algorithm structure may be challenging.
Promotes Uniform Design: It ensures a consistent algorithm structure across multiple classes or subclasses. This helps maintain a uniform design and facilitates understanding for developers working with the codebase.Increased Complexity: The use of the Template Method can lead to increased complexity in the codebase, especially when dealing with multiple subclasses and variations. Understanding the flow may become challenging as the number of subclasses grows.
Room for Customization: The pattern allows for flexibility by enabling subclasses to customize specific steps of the algorithm. This customization accommodates variations in behavior without altering the overall algorithm.Reduced Coupling: The pattern may lead to tight coupling between the template method and its subclasses. Changes in the template method might necessitate modifications in subclasses, impacting the design's extensibility.
Reduced Code Duplication: The Template Method helps in reducing code duplication by centralizing the common algorithm structure. Changes or updates to the algorithm can be made in one place, affecting all subclasses.Less Effective for Code Modifications: Handling variations in specific steps of the algorithm can be challenging. The template method might become less effective if variations are extensive and require conditional logic.

In summary, the Template Method pattern offers advantages in terms of code reuse, consistent structure, and flexibility for customization. However, it comes with trade-offs such as increased complexity, potential tight coupling, and limited runtime flexibility. Choosing to use the Template Method pattern should consider the specific requirements and design goals of the application.

🤖 Don't fully get this? Learn it with Claude

Stuck on Template Method Pattern? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🎨 Explain it visually

Build the mental picture, not memorization.

I just read a lesson on **Template Method Pattern** (OO & Low-Level Design) and want to truly understand it. Explain Template Method Pattern from first principles using ONE vivid real-world analogy and a visual mental model — draw it as ASCII art or a clear step-by-step diagram — with a concrete example using real numbers. Then ask me one question to check I got the mental picture, and wait for my reply. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🤔 Walk me through it (interactive)

Socratic — adapts to where you're stuck.

Teach me **Template Method Pattern** interactively. Ask me ONE guiding question at a time, wait for my answer, and adapt to my confusion — build the idea with me step by step instead of explaining it all at once. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧪 Quiz me & fix my gaps

Active recall exposes what you missed.

Quiz me on **Template Method Pattern** with 5 questions, easy to tricky, ONE at a time. Tell me if each answer is right; at the end, explain clearly what I got wrong and why. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧠 Make it stick

Intuition + hook + flashcards for long-term memory.

Help me remember **Template Method Pattern** for the long term: give the one-sentence intuition, a memorable hook/mnemonic, a tiny worked example, and 3 active-recall flashcards (Q -> A). If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes