模板設計模式,可以顧名思義,就是要先有個模板,然後可以利用這個模板類做出自己需要的類,通過盡量少的修改。
所以先定義一個模板類:
class MachineTemplate
{
public:
void go()
{
startup();
getParts();
assemble();
testing();
ending();
}
virtual void startup()
{
cout<<"Starting up ..."<
假設這個是通用設計機器人的類,那麼如果想要一個有特征的機器人,就需要修改其中的函數,得到想要的功能。
如我們需要一個killing machine:
// Inheriting class
class KillingMachine : public MachineTemplate
{
string name;
public:
KillingMachine(string n = "No Name") : name(n)
{
}
string getName()
{
return name;
}
void getParts()
{
cout<<"Get gun, get bullets, get missiles ...\n";
}
void assemble()
{
cout<<"Gun up, load up, and missile up, ready for party ...\n";
}
void testing()
{
cout<<"Killing ...\n";
}
};
還需要一個巡邏機器人:
class PatrolMachine : public MachineTemplate
{
string name;
public:
PatrolMachine(string n = "No Name") : name(n)
{
}
string getName()
{
return name;
}
void startup()
{
cout<<"Set up patrol line ...\n";
}
void assemble()
{
cout<<"Patroling, make sure the street is saft ...\n";
}
void testing()
{
cout<<"Checking if this object is danger ...\n";
}
void ending()
{
cout<<"Patroling is over, getting back to station ...\n";
}
};
可以看到這兩個特別的機器人都是通過修改其中的一些函數,得到一個特別的類的。
所以通過兩步就完成了應用模板模式了。
最後測試:
void Template_Run_1()
{
KillingMachine killer;
PatrolMachine patrol("UTV_0001");
cout<<"Killing Machine:\n";
cout<
