Conceptly
← All Concepts
πŸ“

Template Method

BehavioralA pattern that fixes the algorithm skeleton and delegates specific steps to subclasses

Template Method is a behavioral pattern that defines the overall structure of an algorithm in a parent-class method and delegates the implementation of certain steps to subclasses. The skeleton is managed in one place; only the way the details are filled in varies.

β–ΆArchitecture Diagram

πŸ” Structure

Dashed line animations indicate the flow direction of data or requests

Why do you need it?

It is common to have similar algorithms implemented with slight variations in multiple places. If the read-transform-save flow is the same but the CSV processing code and the JSON processing code each copy the entire flow, two problems emerge. One is that a bug found in the shared flow must be fixed in every copy. The other is that every new format means another copy of the same skeleton code. Duplicating core logic turns the cost of change from linear to multiplicative.

Why did this approach emerge?

The earliest approach to software reuse was extracting common code into library functions. But when the algorithm skeleton itself -- including call order, pre/post processing, and exception recovery -- needed reuse, function-level extraction fell short. Reusing control flow required a structure that 'fixes the skeleton and leaves only holes open.' Template Method established itself as the most fundamental inheritance-based reuse pattern in the GoF catalog for this reason. Today, framework lifecycle hooks, test framework setUp/tearDown, and build-system step-based extension points are all variations of this structure.

How does it work inside?

Template Method's key feature is that a single method in the parent class (templateMethod) defines the algorithm's full sequence. Inside it, steps like step1(), step2(), and hook() are called in order. Steps come in three kinds. First, fixed steps that the parent class implements completely -- subclasses cannot override them. Second, abstract steps declared as abstract -- subclasses must implement them, and these are the algorithm's variable points. Third, hooks with default implementations that can be optionally overridden: use them when you need to extend, or leave the default. The critical aspect is the direction of control. The subclass does not call the parent; the parent's templateMethod() calls the subclass's methods. This inverted control flow (the Hollywood Principle -- 'Don't call us, we'll call you') keeps the execution order pinned in one place instead of scattering across subclasses.

What is it often confused with?

Template Method and Strategy both make the variable parts of an algorithm replaceable, but they take different approaches. Template Method uses inheritance, with the parent class holding the skeleton and subclasses filling in the steps. Strategy uses composition, pulling the entire algorithm into a separate object for runtime replacement. Template Method replaces only certain steps within the algorithm; Strategy replaces the algorithm as a whole. Because it is inheritance-based, deep class hierarchies can reduce flexibility. If there is only one variation point and the skeleton is stable, Template Method is concise. If there are multiple variation points or runtime strategy switching is needed, Strategy is more flexible.

When should you use it?

Template Method is most commonly encountered in frameworks. A framework controlling the execution flow while the developer fills in only specific steps is the quintessential Template Method. For example, in a test framework, the setUp-test execution-tearDown order is fixed by the framework, and the developer writes only the test methods. In a web framework's request handling, the order authentication-authorization-business logic-response formatting is predefined, and only the business logic is implemented in the controller. In a data migration script, the sequence connect-extract-transform-load-verify is fixed, with only the transform step being swapped -- also Template Method. There are cases where the pattern does not fit. When the skeleton itself changes frequently, the inheritance hierarchy becomes a burden. When step order is conditional rather than fixed, Template Method's premise breaks and a different approach is needed.

Framework extension points -- implementing lifecycle methods (onCreate, onDestroy) in subclassesData processing pipeline -- fixing the read-transform-save flow and swapping only the transform logicTest framework -- replacing only the test within a fixed setUp-test execution-tearDown structureDocument generation -- fixing the analyze-render-output sequence and swapping only the rendering method (PDF, HTML, Markdown)