BehavioralverifiedVerified

Template Method

Defines the skeleton of an algorithm in a base class, deferring certain steps to subclasses without changing the algorithm's overall structure.

Coming Soon

errorWhat Problem Does the Template Method Pattern Solve?

When multiple classes share the same algorithm structure but differ only in specific steps, duplicating the skeleton across subclasses leads to code repetition and divergence. Any change to the overall flow must be replicated in every copy, making maintenance error-prone.

check_circleHow the Template Method Pattern Works

Declare the algorithm's skeleton as a final method in the base class, calling abstract 'hook' methods at variation points. Subclasses override only the hook methods to supply their specific implementations. The base class controls the invariant structure while subclasses control the variant details.

Template Method Pattern Architecture

hourglass_empty

Rendering diagram...

Implementation by Language

lightbulb

Template Method Pattern in the Real World

Consider a recipe for baking bread. The overall process—mix, knead, let rise, bake, cool—is fixed. But the specific flour blend, kneading technique, and baking temperature are decisions left to the baker. The cookbook provides the invariant sequence; individual bakers customize the steps that can vary without disrupting the overall process.

Frequently Asked Questions

helpWhat is the difference between Template Method and Strategy?

Template Method uses inheritance — a base class defines the algorithm skeleton with abstract steps that subclasses override. Strategy uses composition — the algorithm is injected as a separate object. Template Method changes parts of an algorithm; Strategy replaces the entire algorithm.

helpIs Template Method still relevant with modern composition-based designs?

Yes, but its usage has shifted. In frameworks (React class components, Django views, JUnit test cases), Template Method defines lifecycle hooks that developers override. While composition is often preferred for application code, Template Method remains the backbone of many framework APIs.