Skip to main content
Design Patterns 80 XP · 8 min

Template Method: Algorithm Skeleton

Define the skeleton of an algorithm in a superclass, but let subclasses override specific steps without changing its structure.

Showing
Ad (728×90)

Why this matters

When you have multiple classes that follow the same algorithm but differ only in certain steps, the temptation is to copy-paste the skeleton and tweak the differences. Now you have two (or ten) copies of the same control flow to keep in sync. Template Method solves this with the oldest trick in object-oriented programming: put the invariant skeleton in the base class as a template method, declare the variable steps as abstract, and let subclasses fill them in.

The problem

Bad

The solution

Good

Template Method vs Strategy

Both patterns vary parts of an algorithm, but they use different mechanisms. Template Method uses inheritance — the skeleton lives in the parent, variations go in subclasses. Strategy uses composition — the skeleton delegates to an injected strategy object. Template Method is simpler but less flexible (you can't change behavior at runtime); Strategy is more flexible but requires an extra object. Choose Template Method when the algorithm is truly fixed and subclassing is natural.

Key takeaway

Template Method is inheritance doing its one real job: fixing the structure, varying the details — the skeleton stays in the parent, the flesh in the subclass.

Done with this lesson?

Mark it complete to earn XP and track your progress.