SOLID & Design Patterns Interview Question #41

What is the Template Method Pattern?

Structural, Creational & Behavioral Patterns Mid-Level Intermediate

Quick Interview Answer

The Template Method Pattern defines the overall sequence of an algorithm in a base type while allowing subclasses to customize selected steps. The invariant workflow remains in the base class.

Detailed Explanation

The Template Method Pattern defines the overall sequence of an algorithm in a base type while allowing subclasses to customize selected steps. The invariant workflow remains in the base class.

It can be useful when several processes share the same sequence but differ in a few operations. Because it relies on inheritance, composition with Strategy is often preferable when runtime flexibility is important.

Code Example

public abstract class Importer
{
    public void Import()
    {
        Read();
        Validate();
        Save();
    }

    protected abstract void Read();
    protected abstract void Validate();
    protected abstract void Save();
}