Skip to main content

What is the idea behind the Template Method pattern?

The Template Method pattern defines the skeleton (structure) of an algorithm in a base class, letting subclasses override individual steps without changing the overall sequence of actions.


1. The Main Idea

Define the algorithm's "template" in one place (in the superclass), but let subclasses change specific steps, while keeping the overall order.

In other words:

  • the base class manages the execution order,
  • the child classes manage the implementation details.

2. Example (Java)

An Abstract Class With the Template Method

java
abstract class DataProcessor { // Template method public final void processData() { readData(); processDataInternal(); saveData(); } protected abstract void readData(); protected abstract void processDataInternal(); protected void saveData() { System.out.println("Saving data to the database..."); } }

Concrete Implementations

java
class CSVProcessor extends DataProcessor { protected void readData() { System.out.println("Reading a CSV file"); } protected void processDataInternal() { System.out.println("Parsing CSV rows"); } } class JSONProcessor extends DataProcessor { protected void readData() { System.out.println("Reading a JSON file"); } protected void processDataInternal() { System.out.println("Parsing the JSON structure"); } }

Usage

java
DataProcessor processor = new CSVProcessor(); processor.processData();

Result:

javascript
Reading a CSV file Parsing CSV rows Saving data to the database...

3. What Happens

  • The processData() method fixes the algorithm's structure.
  • Subclasses override only the "blanks" (readData(), processDataInternal()), without changing the "skeleton" of the process itself.
  • processData() is declared final to forbid changing the sequence of steps.

4. Where This Applies

  • When you need to guarantee the same sequence of actions, while allowing different implementations of the details.

    For example: generating reports, processing files, rendering pages.

  • When part of the algorithm is shared, while another part varies from subclass to subclass.

  • When you need to control the "lifecycle" of an operation, while letting child classes plug in their own logic.


5. Advantages

  • Removes duplication of shared logic.
  • Makes the process extensible without rewriting the base algorithm.
  • Guarantees the correct order of steps.

6. Disadvantages

  • Strong dependency between the superclass and the subclasses.
  • Hard to maintain if the algorithm is too complex or changes often.

Conclusion

The Template Method pattern sets the algorithm's "frame", delegating the specific details to subclasses.

Summary:

The base class decides "what to do and in what order", while the subclasses decide "exactly how to do it".

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.