Skip to main content

Sign in to CleanKata

Track your progress, earn XP, and unlock every lesson.

By signing in you agree to our Terms of Use and Privacy Policy.

Design Patterns80 XP8 min

Template Method: Algorithm Skeleton

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

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.

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.

πŸ”§ Some exercises may still have errors. If something seems wrong, use the Feedback button (bottom-right of the page) to report it β€” it helps us fix it fast.

Hint: 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.

βœ— Your version

Template Method: Algorithm Skeleton β€” CleanKata β€” CleanKata