// // // // // // // // //
///2013.2.9
// // // // // // // // //
今天是大年三十,
笔者在这里祝大家新年快乐哈。
电视台里还在播放春晚,
外面放着鞭炮,
很有过年的气息(笔者依旧在这里敲代码,尽管)。
其实近些年春晚还是有不少争议的,
先不论其内容如何,
有很多人批判其形式一成不变,
每年都是这个模式:
while(!End)
{
开场舞->唱唱歌->演演小品->主持人讲几个冷笑话->唱唱歌->说说相声->主持人讲讲冷冷笑话
->唱唱歌->刘谦来表演个魔术->主持人讲讲冷笑话;
}
难忘今宵();
return 0;
恩,春晚终于有价值了,
因为它可以作为我们今天的例子来讲解这个设计模式:Template.
【核心】当不同程序逻辑相同,具体算法不同时,使用此模式。
就像每年的春晚形式(逻辑顺序)相同,
而具体内容(算法)不同。
【UML图】
这个模式最大的特点是使用继承而非组合去实现的。
严格意义上来讲,
这属于松耦合。
凡是耦合必然会带来程序调整不方便的问题,
Template也不例外。
不过,
与其解决目标相似的Strategy模式却正好使用组合来弥补这个缺陷。
示例代码:
【大致思路】
Template类的Execute方法的执行是依照一定的逻辑顺序进行的(firstStep->secondStep)。
然而firstStep与secondStep的具体实现算法却在其衍生类中具有不同的内部算法。
Template.h
#ifndef _TEMPLATE_H_ #define _TEMPLATE_H_ class Template { public: Template(){} ~Template(){} void Execute(); protected: virtual void firstStep() = 0; virtual void secondStep() = 0; }; class TypeOne:public Template { public: TypeOne(){} ~TypeOne(){} protected: virtual void firstStep(); virtual void secondStep(); }; class TypeTwo:public Template { public: TypeTwo(){} ~TypeTwo(){} protected: virtual void firstStep(); virtual void secondStep(); }; #endif
Template.cpp
#include"Template.h" #include<iostream> using namespace std; void Template::Execute() { cout<<"Execute..."<<endl; this->firstStep(); this->secondStep(); cout<<endl; } void TypeOne::firstStep() { cout<<"Under type One's first step ->"; } void TypeOne::secondStep() { cout<<"Under type One's second step..."<<endl; } void TypeTwo::firstStep() { cout<<"Under type Two's first step ->"; } void TypeTwo::secondStep() { cout<<"Under type Two's second step..."<<endl; }
main.cpp
#include"Template.h" int main() { Template* typeOne = new TypeOne(); Template* typeTwo= new TypeTwo(); typeOne->Execute(); typeTwo->Execute(); return 0; }
运行结果:
【注意事项】
正如上文所描述的那样,
这个模式的使用也因为其实现方式而受到了一定限制。
但是具体使用起来还是很方便的。
接下来请大家注意Strategy模式的实现,
从而弄清楚二者之间的区别与联系。