A textbook use case for the Template Method pattern is a data-import pipeline that reads from different sources but always follows the same overall steps. The base class fixes the sequence of steps while subclasses supply the source-specific details.
Key Points: • The invariant steps are read, parse, and save; only the read/parse logic differs by source. • A base class defines a final template method that calls readData(), parseData(), and saveData() in order. • Subclasses such as FileDataProcessor, DatabaseDataProcessor, and ApiDataProcessor override just the steps that vary. • Common steps like saveData() can have a default implementation in the base class and be reused by every subclass. • The overall algorithm's shape stays fixed and easy to reason about, even as new data sources are added.
Example: A ReportGenerator base class could define generate() as fetch → transform → render, with a PdfReportGenerator and CsvReportGenerator overriding only render() while sharing fetch and transform.
Interview Tip: A concise interview answer is:
"I'd use Template Method whenever I have a fixed multi-step process but the individual steps vary by case, like importing data from files, databases, or an API. The base class locks in the read-parse-save sequence, and each subclass only overrides the steps specific to its data source."