Design Pattern Template 模板设计模式

模板设计模式,可以顾名思义,就是要先有个模板,然后可以利用这个模板类做出自己需要的类,通过尽量少的修改。

所以先定义一个模板类:

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();
}




  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值