Home/Learn/Java A–Z/Template Method Pattern

Template Method Pattern

Intermediate
Design Patterns

Template Method defines the skeleton of an algorithm in a base class, deferring specific steps to subclasses.

Overview

The Template Method pattern defines the outline of an algorithm in an abstract base class, leaving specific steps as abstract methods for subclasses to implement. The base class controls the overall flow; subclasses customize individual steps. This is a classic application of the Hollywood Principle: "Don't call us, we'll call you." Spring's JdbcTemplate, AbstractList, and Servlet's service() method all use this pattern.

Template Method Implementation

The template method is typically final (preventing subclasses from overriding the algorithm structure). Abstract methods define the customizable steps. Hook methods are optional overridable steps with default implementations — subclasses override them only if needed.

TemplateMethod.java
// Abstract class with template method
public abstract class DataExporter {

    // Template method — defines the algorithm skeleton
    public final void export(String destination) {
        List<Object> data = fetchData();
        List<Object> validated = validate(data);
        String formatted = format(validated);
        write(formatted, destination);
        if (shouldNotify()) {           // hook method
            sendNotification(destination);
        }
    }

    // Steps subclasses must implement
    protected abstract List<Object> fetchData();
    protected abstract String format(List<Object> data);

    // Step with default implementation
    protected List<Object> validate(List<Object> data) {
        return data.stream()
            .filter(Objects::nonNull)
            .collect(Collectors.toList());
    }

    // Hook method — optional override
    protected boolean shouldNotify() { return false; }

    private void write(String data, String dest) {
        Files.writeString(Path.of(dest), data);
    }

    private void sendNotification(String dest) {
        System.out.println("Export complete: " + dest);
    }
}

// Subclass — implements specific steps
public class CsvExporter extends DataExporter {
    @Override
    protected List<Object> fetchData() { return userRepository.findAll(); }

    @Override
    protected String format(List<Object> data) {
        return data.stream().map(Object::toString)
            .collect(Collectors.joining("\n"));
    }

    @Override
    protected boolean shouldNotify() { return true; } // override hook
}

Template Method in the JDK

The JDK uses Template Method extensively:

- AbstractList: implements iterator(), contains(), indexOf() in terms of abstract get(int) and size() - HttpServlet: service() dispatches to doGet(), doPost() etc — you override the specific method - Comparable: sort algorithms call compareTo() — you implement the comparison step - InputStream: read(byte[]) is implemented in terms of abstract read()

AbstractListExample.java
// AbstractList — template method in action
public class RangeList extends AbstractList<Integer> {
    private final int start, end;

    public RangeList(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    public Integer get(int index) {       // implement abstract step
        if (index < 0 || index >= size())
            throw new IndexOutOfBoundsException(index);
        return start + index;
    }

    @Override
    public int size() {                   // implement abstract step
        return end - start;
    }

    // AbstractList provides: iterator(), contains(), indexOf(),
    // subList(), equals(), hashCode() — all built on get() + size()
}

RangeList range = new RangeList(1, 6);
System.out.println(range);             // [1, 2, 3, 4, 5]
System.out.println(range.contains(3)); // true

Template Method vs Strategy

Both patterns vary parts of an algorithm. The difference is how: Template Method uses inheritance — the variant is a method in a subclass. Strategy uses composition — the variant is an injected object.

Template Method is simpler but less flexible (requires subclassing). Strategy allows runtime switching. Modern Java favors Strategy (lambdas) over Template Method for flexibility, but Template Method is still valuable when the overall algorithm structure is fixed and meaningful base behaviour should be reused.

TemplateVsStrategy.java
// Template Method (inheritance — fixed structure)
abstract class ReportGenerator {
    final String generate() { // template
        String data = collectData();
        return format(data);
    }
    abstract String collectData();
    abstract String format(String data);
}

// Strategy (composition — flexible)
class ReportService {
    private final Supplier<String> dataCollector;
    private final UnaryOperator<String> formatter;

    ReportService(Supplier<String> collector, UnaryOperator<String> fmt) {
        this.dataCollector = collector;
        this.formatter     = fmt;
    }

    String generate() {
        return formatter.apply(dataCollector.get());
    }
}

// Strategy is more flexible — swap algorithms at runtime
ReportService svc = new ReportService(
    db::fetchAllUsers,  // swap this for different data source
    CsvFormatter::format // swap this for different format
);

Key Points to Remember

  • Template method is final; subclasses implement abstract steps and optionally override hooks.
  • The Hollywood Principle: the base class calls subclass methods, not the reverse.
  • AbstractList, HttpServlet, and InputStream use Template Method in the JDK.
  • Hook methods are optional steps with default (often no-op) implementations.
  • Template Method = inheritance-based variation; Strategy = composition-based — prefer Strategy for flexibility.

Practice Template Method Pattern in the Playground

Run and modify code directly in your browser - no setup needed.

Interview Questions

Sign in to ask Aria
1

What is the Hollywood Principle and how does Template Method implement it?

MediumGoogle
2

What is the difference between abstract methods and hook methods in Template Method?

MediumAmazon
3

Why is the template method typically declared final?

EasyOracle
4

How does AbstractList use Template Method? What methods must you implement?

MediumMicrosoft
5

What is the difference between Template Method and Strategy patterns?

MediumNetflix

Ask Aria about Template Method Pattern

Your personal AI tutor — ask anything about this concept