All 15 Design Patterns in Java questions
More in Design Patterns in Java
Advertisement
Back to results for “Testing Strategy”
Java › Design Patterns in Java

What is the Template Method pattern, and how is it used to define the skeleton of an algorithm while letting subclasses customize specific steps?

Intermediate

Answer

Template Method defines the overall structure/sequence of an algorithm in a base class's (typically final) method, calling out to one or more abstract or overridable "hook" methods that subclasses implement to customize specific steps, without subclasses being able to alter the overall algorithm's sequence itself -- this is a common pattern in framework design, where the framework controls the overall flow (like a test runner's setup-execute-teardown sequence) while application code plugs in the specific behavior for individual steps.
public abstract class DataProcessor {
    public final void process() {  // template method -- final, defines fixed algorithm structure
        loadData();
        validate();
        transform();
        saveResults();
    }
    protected abstract void loadData();
    protected abstract void transform();
    protected void validate() { /* default implementation, can be overridden */ }
    protected void saveResults() { System.out.println("Saving..."); }
}

class CsvProcessor extends DataProcessor {
    protected void loadData() { /* CSV-specific loading */ }
    protected void transform() { /* CSV-specific transformation */ }
}
Real-world example A test framework's base test class defines a final runTest() template method calling setUp(), executeTest(), and tearDown() in a fixed sequence, with individual test classes only needing to override the specific steps relevant to them, guaranteeing every test consistently follows the same overall lifecycle regardless of what each individual test actually does.

Common follow-ups: How does Template Method differ from the Strategy pattern, given both involve customizable behavior?;Why is marking the template method itself as final considered important to preserving the pattern's intent?