Skip to content
Veltoryx Technologies
ProLesson 7.1Intermediate8 min readUpdated 31 October 2026

Template Method Pattern

Learn how to fix the order of an algorithm in a base class while letting subclasses fill in the steps that differ, using a file importer, and how it compares with Strategy.

Think about how a recipe book describes making a hot drink. The steps are always the same: boil water, brew the drink, pour it into a cup, add extras. For tea, "brew" means soaking tea leaves. For coffee, "brew" means filtering ground beans. The order of the steps and the general plan stay the same, and only a few steps change from one drink to the next.

The Template Method pattern captures this in code. A base class defines the skeleton of an algorithm: the fixed order of steps. Some steps are written once in the base class, and others are left empty for subclasses to fill in. The base class stays in control of the flow, and the subclasses supply the details.

01The problem: the same steps, copied with small differences

A company imports customer data from files that partners send. Some partners send CSV files and others send JSON. The overall process is identical:

  1. read the file,
  2. parse the text into rows,
  3. check that the rows are valid,
  4. save the rows to the database.

Only step 2, parsing, depends on the format. A first version often copies the whole process for each format:

Before: two classes repeat the same process
public class CsvImporter {
    public int importFile(Path file) throws IOException {
        String text = Files.readString(file);
        List<Row> rows = parseCsv(text);                 // the only difference
        if (rows.isEmpty()) throw new IllegalArgumentException("No records");
        saveToDatabase(rows);
        return rows.size();
    }
    // parseCsv(...) and saveToDatabase(...) here
}

public class JsonImporter {
    public int importFile(Path file) throws IOException {
        String text = Files.readString(file);
        List<Row> rows = parseJson(text);                // the only difference
        if (rows.isEmpty()) throw new IllegalArgumentException("No records");
        saveToDatabase(rows);
        return rows.size();
    }
    // parseJson(...) and saveToDatabase(...) here
}

The two classes are nearly the same. This duplicated code is a risk: when a bug is fixed in one class, someone must remember the other one. A third format, XML, makes it three copies. This violates the DRY rule from Module 2, the knowledge "how an import works" is written in several places.

Loading the rest of the lesson…