Template Method

Define the skeleton of an algorithm in an operation, deferring some steps to subclasses; Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure. Use to implement the invariant parts of an algorithm once and let subclasses supply the varying behavior.

Examples:

  • A data-mining application extracts data from DOC, CSV, and PDF files. All three formats follow the same pipeline: open file → extract raw data → parse → analyze → produce report → close file. Template Method places this skeleton in a base DataMiner class; only the 'extract raw data' and 'parse' steps are abstract — each format subclass overrides only what differs, sharing the rest of the pipeline.
class AbstractClass {
public:
  void TemplateMethod() { // skeleton
    PrimitiveOp1();
    PrimitiveOp2();
  }
protected:
  virtual void PrimitiveOp1() = 0;
  virtual void PrimitiveOp2() = 0;
};
class ConcreteClass : public AbstractClass {
  void PrimitiveOp1() override { /* step 1 */ }
  void PrimitiveOp2() override { /* step 2 */ }
};