1.模板模式的定义与类图
从这里开始进入行为型模式阶段,行为型模式主要是指用来对类或对象怎样交互和怎样分配职责进行描述。
模板模式即指在抽象类中统一操作步骤,并规定好接口,其子类实现接口,从而实现将各个具体的子类和操作步骤解耦合。通俗点说,就是模板类定义了一个/多个确定接口逻辑与步骤的函数,同时定义多个需要重载的接口,子类负责重载这些接口即可,具体的逻辑操作均有基类的逻辑函数来确定,客户端调用时也是直接调用具体子类new出对象,而函数仍是使用基类的逻辑函数。
其类图如下:
类图中,TemplateMethod即为所述的逻辑函数,而Method1和Method2即为接口函数。
2.模板模式的代码实现
本例中使用MakeBicycle作为基类,其中定义了makeWheel,makeBrake和makeCushion三个接口函数,并定义逻辑函数makebicycle,用于实现接口函数的执行逻辑与顺序。两个派生类为Make_NormalBicycle和Make_GreatBicycle,表示两种不同的自行车创造过程。
具体代码如下:
#include <iostream>
#include <string>
using namespace std;
class MakeBicycle
{
public:
void makebicycle() //模板模式的特点就是这个函数,定义了执行的规则与逻辑
{
makeWheel();
makeBrake();
makeCushion();
}
protected:
virtual void makeWheel() = 0;
virtual void makeBrake() = 0;
virtual void makeCushion() = 0;
};
class Make_NormalBicycle : public MakeBicycle
{
public:
void makeWheel()
{
cout << "Make the normal bicycle's wheel!" << endl;
}
void makeBrake()
{
cout << "Make the normal bicycle's brake!" << endl;
}
void makeCushion()
{
cout << "Make the normal bicycle's cushion!" << endl;
}
};
class Make_GreatBicycle : public MakeBicycle
{
public:
void makeWheel()
{
cout << "Make the great bicycle's wheel!" << endl;
}
void makeBrake()
{
cout << "Make the great bicycle's brake!" << endl;
}
void makeCushion()
{
cout << "Make the great bicycle's cushion!" << endl;
}
};
int main()
{
MakeBicycle* normalbicycle = new Make_NormalBicycle;
normalbicycle->makebicycle();
MakeBicycle* greatbicycle = new Make_GreatBicycle;
greatbicycle->makebicycle();
delete normalbicycle;
delete greatbicycle;
return 0;
}