0Pricing
Java Academy · Lesson

Template Method: Defining Algorithm Skeletons

Define the skeleton of an algorithm in a base class and let subclasses fill in the steps.

The Template Method Intent

Template Method defines the skeleton of an algorithm in a base class, deferring some steps to subclasses. Subclasses can override steps without changing the overall structure.

The Abstract Base Class

The base class has the template method (usually final) that orchestrates the steps. Abstract methods represent the varying steps. Concrete methods provide default behavior.

public abstract class DataProcessor {
    // Template method — final, defines the algorithm
    public final void process() {
        readData();
        processData();
        writeResult();
    }
    protected abstract void readData();
    protected abstract void processData();
    protected void writeResult() {
        System.out.println("Result written (default)");
    }
}

All lessons in this course

  1. Observer Pattern: Event Notification
  2. Strategy Pattern: Interchangeable Algorithms
  3. Command Pattern: Encapsulating Actions
  4. Template Method: Defining Algorithm Skeletons
← Back to Java Academy