Design Patterns
Template Method
Running the template takes O(n) time, where n is the number of steps. That's the same cost as writing it out by hand, but organized instead of duplicated.
The idea, in plain English
A template method works like a recipe card. Some steps are fixed, and some are left blank for you to fill in. 'Boil water' and 'pour into cup' never change, but 'brew' and 'add condiments' depend on whether you're making tea or coffee. In code, a base class (a starting blueprint other classes build on) locks in the overall order of steps. Each subclass — a class built from that blueprint — fills in just the steps that differ.
How it works
- 1You write one method in a base class that runs a fixed sequence of steps, in order.
- 2You write the steps that never change directly in the base class.
- 3You leave the steps that do change unwritten in the base class. Each subclass fills them in its own way.
When you'd use it
Use this when several processes share the same overall shape, but differ in a few specific steps. Examples: brewing a hot drink, running a report, or processing different file formats through the same pipeline.
Common beginner mistakes
- Don't copy-paste the whole sequence for every variant. Pull the shared steps into one template instead.
- Always override every required step. Skipping one can silently fall back to base behavior that doesn't fit that subclass.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Tea: Boil water -> Steep tea -> Pour in cup -> Add lemon
Coffee: Boil water -> Brew coffee grounds -> Pour in cup -> Add sugar and milkNot sure this is the right topic? See the learning paths → or where this leads →