Video in progress

Strong Middle 🧱 OOP and SOLID

What is the difference between the Template Method and Strategy patterns, and when do you choose each?

Both separate the varying part of an algorithm. Template Method does it through inheritance: the skeleton is in the parent class and the steps are in the child class. Strategy does it through composition: the varying part is a separate object that is swapped at runtime.

📖 Answer

One task: importing from CSV and Excel.

Template Method:

abstract class Importer {
    public final ImportResult run(InputStream in) {
        var rows = parse(in);          // varies
        var valid = validate(rows);    // shared
        return save(valid);            // shared
    }
    protected abstract List<Row> parse(InputStream in);
}

class CsvImporter extends Importer { ... }
class ExcelImporter extends Importer { ... }

Strategy:

interface RowParser { List<Row> parse(InputStream in); }

class Importer {
    private final RowParser parser;
    Importer(RowParser parser) { this.parser = parser; }
    public ImportResult run(InputStream in) { ... parser.parse(in) ... }
}
Template Method Strategy
Mechanism inheritance composition
When it is bound at compile time at runtime
Variation along several axes the number of classes grows (CSV×UTF8, CSV×CP1251...) strategies can be combined
Testing the abstract class through a subclass the parser separately, the importer with a fake

When Template Method is good: the number of steps is small, the skeleton is fixed, and the framework expects you to fill in only the "holes". Despite its name, JdbcTemplate actually uses callbacks (strategy), while AbstractRoutingDataSource and OncePerRequestFilter are real template methods.

I usually start with Strategy: it is easy to test, and when the varying part has two axes, the combinations don't explode. In Java a strategy is often just a lambda: Function<InputStream, List<Row>>.