一,简介
模板方法模式,定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法得结构即可重定义该算法得某些特定步骤。
二,角色
AbstractClass
实现了一个模板方法,定义了算法的骨架。并定义个Operation步骤
ConcreteClass
实现Operation以完成算法中与特定子类相关的步骤
三,举例
以玩游戏为例
1.类图
2,代码
class AbstractGame {//抽象类,其实也就是抽象模板
public:
virtual void initialize() = 0;//一些抽象行为
virtual void startPaly() = 0;
virtual void endPlay() = 0;
void play() {//模板方法,给出了逻辑的骨架
//初始化游戏
initialize();
//开始游戏
startPaly();
//结束游戏
endPlay();
}
};
class Football :public AbstractGame {
public:
virtual void initialize() {
cout << "Football Game Initialized!Start playing." << endl;
}
virtual void startPaly() {
cout << "Football Game Started. Enjoy the game!" << endl;
}
virtual void endPlay() {
cout << "Football Game Finished!" << endl;
}
};
class Baseball :public AbstractGame {
public:
virtual void initialize() {
cout << "Baseball Game Initialized!Start playing." << endl;
}
virtual void startPaly() {
cout << "Baseball Game Started. Enjoy the game!" << endl;
}
virtual void endPlay() {
cout << "Baseball Game Finished!" << endl;
}
};
int main()
{
AbstractGame * game = new Football();
game->play();
game = new Baseball();
game->play();
system("pause");
return 0;
}
四,优缺点
优点:
1、封装不变部分,扩展可变部分。
2、提取公共代码,便于维护。
3、行为由父类控制,子类实现。
缺点:每一个不同的实现都需要一个子类来实现,导致类的个数增加,使得系统更加庞大。
五,使用场景
1、有多个子类共有的方法,且逻辑相同。
2、重要的、复杂的方法,可以考虑作为模板方法。
如:
1、在造房子的时候,地基、走线、水管都一样,只有在建筑的后期才有加壁橱加栅栏等差异。
2、西游记里面菩萨定好的 81 难,这就是一个顶层的逻辑骨架。