Template method pattern
The template method defines an algorithm skeleton in a base class while letting subclasses override specific steps, enforcing the Hollywood Principle: don't call us, we'll call you.
Introduction
The Template Method pattern defines an algorithm's invariant sequence in a base class and lets subclasses provide or customize selected steps. The base class controls the order; subclasses supply the variation points.
TL;DR / mental model
Think of the base class as a recipe with a fixed order. Abstract steps are required ingredients, hooks are optional additions, and subclasses fill in the details without rewriting the recipe itself.
Problem and Context
Your data export pipeline handles CSV, JSON, and XML. Each format follows the same sequence: fetch data, validate it, format it, and write the output. But every export class duplicates the algorithm skeleton.
Three exporters, one algorithm, three copies. When the team adds a "compress before writing" step, someone forgets to add it to the XML exporter. Bugs hide in the duplication. Here is what changes when you apply Template Method.
Participants and Structure
DataExporter owns the algorithm skeleton in export(). The format() method is abstract because every exporter must provide its own formatting logic. onExportComplete() is a hook with an empty default so subclasses can optionally add behavior (like sending a notification) without being forced to.
Idiomatic Example and Implementation Notes
The key design decision is which steps are abstract (required overrides) versus hooks (optional overrides with defaults). Abstract steps force subclasses to provide behavior. Hooks let them opt in without obligation.
The Hollywood Principle
"Don't call us, we'll call you." The base class calls the subclass methods at the right time. Subclasses never call the template method or decide when steps run. They just fill in the blanks.
Continue Reading with Premium
Unlock this article and every other in-depth system design guide on the platform with SDEpedia Premium.
Related Articles
The strategy pattern extracts a family of algorithms behind an interface so the client can swap behaviors at runtime without touching the context class.
The factory method replaces direct constructor calls with a method that subclasses can override to return different types. Callers depend on an abstraction, not a concrete class.
Learn the five SOLID principles by building a real order-processing system in Java, with before and after code for every principle.