Java Omnibus
OOAD & Architecture / GoF patterns / Behavioral / Template Method Pattern in Java
GoF Behavioral Java Order Management
GoF Pattern

Template Method helps when one process skeleton is stable but a few steps should vary in controlled ways.

Define the skeleton of an algorithm in one operation and let subclasses redefine certain steps without changing the algorithm’s overall structure.

Intent

What the pattern is trying to do

Define the skeleton of an algorithm in one operation and let subclasses redefine certain steps without changing the algorithm’s overall structure.

Problem

What force creates the need

Several processes follow the same broad sequence, but a few steps differ and repeated duplication is growing.

Solution

How the pattern responds

Keep the stable algorithm in a base class and expose specific hook methods for subclasses to vary.

Structure

How the moving parts fit together

A base class defines the template flow and delegates specific steps to overridable methods implemented by subclasses.

Java Example

Java example in the Order Management domain

Template Method Pattern in Java example
package org.javaomnibus.ecommerce.gof.behavioral;

public abstract class ReceiptRenderer {
    public final String render(Order order) {
        return header(order) + body(order) + footer(order);
    }

    protected String header(Order order) {
        return "Receipt\n";
    }

    protected abstract String body(Order order);

    protected String footer(Order order) {
        return "\nThank you";
    }
}
Code Walkthrough

Step by step

  1. The render method defines the stable process skeleton.
  2. Subclasses vary only the intended steps.
  3. This preserves the overall algorithm while allowing controlled customization.
  4. Template Method is strongest when the sequence is genuinely stable.
When To Use

Where this pattern helps

  • When one algorithm structure is fixed but a few steps vary
  • When inheritance-based variation is acceptable and explicit
When Not To Use

When a simpler design is better

  • When composition would be more flexible than inheritance
  • When the process skeleton itself is unstable
Trade-Offs

What this pattern costs

  • Inheritance makes variation less flexible than composition-based approaches
  • Overuse can create brittle base classes
Modern Relevance

How this fits today

Template Method still appears in framework base classes, rendering flows, import/export pipelines, and testing scaffolds, though many teams now prefer composition where practical.

Common Misuse

Where teams get it wrong

Using Template Method where strategies or composed collaborators would be clearer can trap the design in rigid inheritance hierarchies.

Related Patterns

Compare with nearby choices


What To Read Next