BehavioralC#verifiedVerified

Template Method Pattern in C#

Defines the skeleton of an algorithm in a base class, deferring certain steps to subclasses without changing the algorithm's overall structure.

How to Implement the Template Method Pattern in C#

1Step 1: Define abstract class with the template method

public abstract class DataParser
{
    // Template method defines the algorithm skeleton
    public string Parse(string rawData)
    {
        var opened = OpenFile(rawData);
        var extracted = ExtractData(opened);
        var parsed = ParseData(extracted);
        return FormatOutput(parsed);
    }

2Step 2: Abstract steps to be implemented by subclasses

    protected abstract string OpenFile(string path);
    protected abstract string[] ExtractData(string raw);
    protected abstract object[] ParseData(string[] rows);

    // Hook method with default behavior
    protected virtual string FormatOutput(object[] data) =>
        string.Join(", ", data);
}

3Step 3: Concrete implementation

public class CsvParser : DataParser
{
    protected override string OpenFile(string path) =>
        $"Contents of {path}";

    protected override string[] ExtractData(string raw) =>
        raw.Split('\n');

    protected override object[] ParseData(string[] rows) =>
        rows.Select(r => (object)r.Split(',')).ToArray();
}

Template Method Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Template Method Pattern in the Real World

Consider a recipe for baking bread. The overall process—mix, knead, let rise, bake, cool—is fixed. But the specific flour blend, kneading technique, and baking temperature are decisions left to the baker. The cookbook provides the invariant sequence; individual bakers customize the steps that can vary without disrupting the overall process.