Template Method Pattern
Fix the order of an algorithm's steps in a base class and let subclasses fill in the steps that differ.
Overview
The problem: the same steps, different details
Three importers read sales data from CSV files, JSON files and a database. Each one does the same four things in the same order: open the source, read the rows, clean them, write a summary. Only the first two steps differ. Written as three separate classes, the shared steps are copied three times, and a fix to the cleaning rule has to be made in three places.
Line the three importers up step by step. To open, the CSV and JSON importers open the file, while the database importer connects. To read rows, the CSV importer splits lines on commas, the JSON importer parses an array, and the database importer runs a query. Cleaning the rows and writing the summary are the same in all three.
So two of the four steps vary, and two are the same. The Template Method pattern keeps the shared steps and the order in one place.
Interview questions
- Show the smell Template Method fixes, and the fix.
- What is a hook, and how is it different from an abstract step?
- When would you refactor a Template Method into a Strategy?
- How do you stop a subclass from breaking the algorithm?
- Why do frameworks use Template Method so much?
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio