What is the Template Method pattern?
Answer
The Template Method pattern defines the skeleton of an algorithm in a base class, deferring some steps to subclasses. The base class controls the overall structure (the "template") while subclasses override specific steps without changing the overall algorithm structure. Example — data processing pipeline: abstract class DataProcessor { // Template method -- defines the algorithm structure: public final void process() { readData(); validateData(); processData(); formatOutput(); saveResults(); } // Steps that subclasses must implement: protected abstract void readData(); protected abstract void processData(); // Steps with default implementation (can be overridden): protected void validateData() { System.out.println("Default validation: checking for null"); } protected void formatOutput() { System.out.println("Default formatting: plain text"); } protected void saveResults() { System.out.println("Default: saving to file"); } } class CSVDataProcessor extends DataProcessor { @Override protected void readData() { System.out.println("Reading CSV file"); } @Override protected void processData() { System.out.println("Parsing CSV columns"); } @Override protected void formatOutput() { System.out.println("Formatting as JSON"); // Override default } } class APIDataProcessor extends DataProcessor { @Override protected void readData() { System.out.println("Calling REST API"); } @Override protected void processData() { System.out.println("Deserializing JSON response"); } } // Both use the same algorithm structure: new CSVDataProcessor().process(); new APIDataProcessor().process();. Hook methods: optional override points — base class provides empty implementation: protected void postProcess() {} // Hook -- override if needed. Real examples: JUnit TestCase (setUp, test, tearDown), Java's AbstractList, Spring's JdbcTemplate. vs Strategy: Template Method uses inheritance to vary part of algorithm; Strategy uses composition to vary the whole algorithm.