1. 案例引入:泡茶和咖啡
- 泡茶怎么做的?
准备茶叶,加点枸杞,冲入沸水 - 咖啡怎么调制?
准备咖啡,加点牛奶,冲入沸水
对比泡茶和冲咖啡,需要的步骤是不是很类似? 准备XX,加点YY,冲入热水
于是,抽象出如下的设计:

- makeprocess
{
准备XX;
加点YY;
冲入热水
}
makeprocess 提供一套接口的调用顺序,而具体的函数比如准备XX,加点YY交给子类去实现
#include <iostream>
using namespace std;
class MakeDrink
{
public:
void makeprocess()
{
prepare();
addConditions();
pourinWater();
}
void pourinWater()
{
cout << "pour in water" << endl;
}
virtual void prepare() = 0;
virtual void addConditions() = 0;
};
class MakeTea:public MakeDrink
{
public:
void prepare()
{
cout << "prepare tea" << endl;
}
void addConditions()
{
cout << "add WolfBerry" << endl;
}
};
class MakeCoffe:public MakeDrink
{
public:
void prepare()
{
cout << "prepare coffe" << endl;
}
void addConditions()
{
cout << "add milk" << endl;
}
};
int main()
{
MakeTea tea;
tea.makeprocess();
MakeCoffe coffe;
coffe.makeprocess();
return 0;
}
输出:
prepare tea
add WolfBerry
pour in water
prepare coffe
add milk
pour in water
2. 模板模式一般定义
The Template Method defines the steps of an algorithm and allows subclasses to provide the implementation for one or more steps

对应表格
| AbstractClass | MakeDrink |
| ConcereteClass | MakeTea/MakeCoffe |
| templateMethod() | MakeDrink::makeprocess() |
| primitiveOperation1() | MakeDrink::prepare() |
| primitiveOperation2() | MakeDrink::addConditions() |
3. 模板模式应用的引申 hook
3.1 Hook 定义
With a hook, I can override
the method, or not. It’s my choice.
If I don’t, the abstract class provides a default implementation.
3.2 Hook 实现
示例中如下函数是一个hook,默认返回true。
virtual bool UserwantConditions() // this is a hook method
{
return true;
}
#include <iostream>
using namespace std;
class MakeDrink
{
public:
void makeprocess()
{
prepare();
//where hook applies
if(UserwantConditions() == true)
{
addConditions();
}
pourinWater();
}
void pourinWater()
{
cout << "pour in water" << endl;
}
virtual void prepare() = 0;
virtual void addConditions() = 0;
virtual bool UserwantConditions() // this is a hook method
{
return true;
}
};
class MakeTea:public MakeDrink
{
public:
void prepare()
{
cout << "prepare tea" << endl;
}
void addConditions()
{
cout << "add WolfBerry" << endl;
}
};
class MakeCoffe:public MakeDrink
{
public:
void prepare()
{
cout << "prepare coffe" << endl;
}
void addConditions()
{
cout << "add milk" << endl;
}
bool UserwantConditions()
{
return false;
}
};
int main()
{
MakeTea tea;
tea.makeprocess();
MakeCoffe coffe;
coffe.makeprocess();
return 0;
}
输出:
prepare tea
add WolfBerry
pour in water
prepare coffe
pour in water
332

被折叠的 条评论
为什么被折叠?



