Template Method

1. Usage

  1. Define the skeleton of an algorithm in base class “Template Method”
  2. Steps required concrete implementation define as placeholders in base class
  3. Derifed classes fill-up placeholders with concrete implementations

2. UML class diagram

3. Pros

  1. shields the client from the details of the variant behaviour
  2. quality & productivity – only the variant behaviour needs to be implemented

4. Cons

5. Source code


// From https://sourcemaking.com/design_patterns/template_method/cpp/1
#include <iostream>
using namespace std;

class Base
{
    void a()
    {
        cout << "a  ";
    }
    void c()
    {
        cout << "c  ";
    }
    void e()
    {
        cout << "e  ";
    }
    // 2. Steps requiring peculiar implementations are "placeholders" in base class
    virtual void ph1() = 0;
    virtual void ph2() = 0;
  public:
    // 1. Standardize the skeleton of an algorithm in a base class "template method"
    void execute()
    {
        a();
        ph1();
        c();
        ph2();
        e();
    }
};

class One: public Base
{
    // 3. Derived classes implement placeholder methods
     /*virtual*/void ph1()
    {
        cout << "b  ";
    }
     /*virtual*/void ph2()
    {
        cout << "d  ";
    }
};

class Two: public Base
{
     /*virtual*/void ph1()
    {
        cout << "2  ";
    }
     /*virtual*/void ph2()
    {
        cout << "4  ";
    }
};

int main()
{
  Base *array[] = 
  {
     &One(), &Two()
  };
  for (int i = 0; i < 2; i++)
  {
    array[i]->execute();
    cout << '\n';
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *