Template Method Pattern

Template Method Pattern is one of the Behavioral design pattern.

According to Gang Of Four intent of Template Method Pattern is to 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.


SAMPLE CODE:

#include <iostream>

using namespace std;

class CoffeeTemplate {
private:
    virtual void boilWater()
    {
        cout << "  * Boiling Water" << endl;
    }
    virtual void addMilk()
    {
        cout << "  * Adding Milk" << endl;
    }
    void addSugar()
    {
        cout << "  * Adding Sugar" << endl;
    }

    virtual void addCoffee() = 0;

public:
    void makeCoffee() /* Template Method */
    {
        cout << "Start Making Coffee" << endl;
        boilWater();
        addMilk();
        addCoffee();
        addSugar();
        cout << "Tasty Coffee Ready Enjoy!!!" << endl << endl;
    }
};

class NescafeeCoffee : public CoffeeTemplate {
    void addCoffee()
    {
        cout << "  * Adding Nescafee Coffee Podwer" << endl;
    }
};

class BruCoffee : public CoffeeTemplate {
    void addCoffee()
    {
        cout << "  * Adding Bru Coffee Powder" << endl;
    }
};

class SunriseCoffee : public CoffeeTemplate {
    void addCoffee()
    {
        cout << "  * Adding Sunrise Coffee Powder" << endl;
    }
};

int main()
{
    CoffeeTemplate* coffee = new BruCoffee();
    coffee->makeCoffee();

    coffee = new SunriseCoffee();
    coffee->makeCoffee();
    return 0;
}

OUTPUT:

Start Making Coffee
  * Boiling Water
  * Adding Milk
  * Adding Bru Coffee Powder
  * Adding Sugar
Tasty Coffee Ready Enjoy!!!

Start Making Coffee
  * Boiling Water
  * Adding Milk
  * Adding Sunrise Coffee Powder
  * Adding Sugar
Tasty Coffee Ready Enjoy!!!

                                               INDEX - OTHER DESIGN PATTERNS



No comments:

Post a Comment