模板方法模式:
定义一个操作中算法的框架,而将一些步骤延迟到子类中。模仿方法模式使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
代码如下:
#include <iostream>
using namespace std;class DrinkTemplate
{
public:virtual void BoildWater() = 0;virtual void Brew() = 0;virtual void PourInCup() = 0;virtual void AddSomething() = 0;//模板方法void Make(){BoildWater() ;Brew() ;PourInCup() ;AddSomething();}
};class Coffee :public DrinkTemplate
{
public:virtual void BoildWater(){cout << "煮山泉水" << endl;}virtual void Brew(){cout << "冲泡咖啡" << endl;}virtual void PourInCup(){cout << "咖啡倒入杯中" << endl;}virtual void AddSomething(){cout << "加点糖,牛奶" << endl;}
};class Tea :public DrinkTemplate
{
public:virtual void BoildWater(){cout << "煮矿泉水" << endl;}virtual void Brew(){cout << "冲泡铁观音" << endl;}virtual void PourInCup(){cout << "茶水倒入杯中" << endl;}virtual void AddSomething(){cout << "加点糖,柠檬" << endl;}
};void test01()
{Tea *tea = new Tea;tea->Make();cout << "-----------------------------" << endl;Coffee *coffee = new Coffee;coffee->Make();
}int main()
{test01();return 0;
}
测试结果: