模板方法模式:封装算法在一个抽象类中,在其子类中进行全部或部分的真正的实现
C++示例代码如下:
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
/*
* CONTENTS: DESIGN PATTERN, TEMPLATE METHOD PATTERN
* AUTHOR: YAO H. WANG
* TIME: 2013-11-6 16:43:47
* EDITION: 1
* LINK: http://blog.csdn.net/yaohwang
*
* ALL RIGHTS RESERVED!
*/
class CaffineBeverageWithHook
{
public:
virtual void prepareRecipe() final
{
boilWater();
brew();
pourInCup();
if(customerWantsCondiments())
{
addCondiments();
}
}
void boilWater()
{
cout << "Boiling water" << endl;
}
virtual void brew() = 0;
void pourInCup()
{
cout << "Pouring into cup" << endl;
}
//hook
virtual bool customerWantsCondiments()
{
return true;
}
virtual void addCondiments() = 0;
};
class CoffeeWithHook: public CaffineBeverageWithHook
{
public:
void brew()
{
cout << "Dripping Coffee through filter" << endl;
}
void addCondiments()
{
cout << "Adding Sugar and Milk" << endl;
}
bool customerWantsCondiments()
{
string answer = getUserInput();
if('y' == answer[0])
return true;
else
return false;
}
string getUserInput()
{
string answer;
cout << "Would you like milk and sugar with your coffee (y/n)?" << endl;
cin >> answer;
return answer;
}
};
class TeaWithHook: public CaffineBeverageWithHook
{
public:
void brew()
{
cout << "Steeping the tea" << endl;
}
void addCondiments()
{
cout << "Adding Lemon" << endl;
}
bool customerWantsCondiments()
{
string answer = getUserInput();
if('y' == answer[0])
return true;
else
return false;
}
string getUserInput()
{
string answer;
cout << "Would you like lemon with your tea (y/n)?" << endl;
cin >> answer;
return answer;
}
};
//测试
void main()
{
TeaWithHook teaHook;
CoffeeWithHook coffeeHook;
cout << "Making tea..." << endl;
teaHook.prepareRecipe();
cout << "\nMaking coffee..." << endl;
coffeeHook.prepareRecipe();
}