模板设计模式,可以顾名思义,就是要先有个模板,然后可以利用这个模板类做出自己需要的类,通过尽量少的修改。
所以先定义一个模板类:
class MachineTemplate
{
public:
void go()
{
startup();
getParts();
assemble();
testing();
ending();
}
virtual void startup()
{
cout<<"Starting up ..."<<std::endl;
}
virtual void getParts()
{
cout<<"Get parts needed ...\n";
}
virtual void assemble()
{
cout<<"Assembling ...\n";
}
virtual void testing()
{
cout<<"Testing ...\n";
}
virtual void ending()
{
cout<<"Ending ...\n";
}
};
假设这个是通用设计机器人的类,那么如果想要一个有特征的机器人,就需要修改其中的函数,得到想要的功能。
如我们需要一个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<<killer.getName()<<" : "<<endl;
killer.go();
cout<<"\nPatrol Machin:\n";
cout<<patrol.getName()<<" : "<<endl;
patrol.go();
}