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 the base class with the template method

class DataProcessor {
public:
    virtual ~DataProcessor() = default;

    // Template method — defines the algorithm skeleton
    void process() {
        auto data = readData();
        auto parsed = parseData(data);
        auto result = transform(parsed);
        save(result);
    }

protected:
    // Steps to be overridden by subclasses
    virtual std::string readData() = 0;
    virtual std::vector<std::string> parseData(const std::string& raw) = 0;

    // Optional hook with default behavior
    virtual std::string transform(const std::vector<std::string>& data) {
        std::string result;
        for (const auto& item : data) result += item + "\n";
        return result;
    }

    virtual void save(const std::string& result) {
        std::cout << "Saved: " << result;
    }
};

2Step 2: Concrete implementation

class CsvProcessor : public DataProcessor {
protected:
    std::string readData() override {
        return "name,age\nAlice,30\nBob,25";
    }
    std::vector<std::string> parseData(const std::string& raw) override {
        std::vector<std::string> lines;
        size_t pos = 0, prev = 0;
        while ((pos = raw.find('\n', prev)) != std::string::npos) {
            lines.push_back(raw.substr(prev, pos - prev));
            prev = pos + 1;
        }
        lines.push_back(raw.substr(prev));
        return lines;
    }
};

int main() {
    CsvProcessor processor;
    processor.process();
}

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.