c++设计模式之原型模式Prototype

/************************************************************************/
/*							  原型模式                                  */
/************************************************************************/





/*
	这里以这样一个例子为大家解释:
	大家都见过西游记中的悟空,可以变出n个自己
	悟空的真身就是原型,而它通过“克隆”的方法制造出自己


    c++中原型模式的实现主要是通过拷贝构造函数实现的

*/
#include <IOSTREAM>
using namespace std;




/*
	原型类,声明一个克隆自己的接口
*/
class Prototype
{
public:
	virtual ~Prototype(){};

	//定义一个克隆的抽象函数
	virtual Prototype *Clone() const = 0 ;


protected:
	Prototype()
	{

	}

};



class Wukong : public Prototype
{
public:

	Wukong(int age,char *name)
	{
		this->age = age;
		this->name = name;
	}


	//拷贝构造函数
	Wukong(const Wukong&C)
	{
		age=C.age;
		name = new char[100];
		strcpy(name,C.name);
	}

	//克隆函数
	Prototype *Clone() const
	{
		//当类对象以参数的形式传递时会调用拷贝构造函数
		return new Wukong(*this);
	}


	void Display()
	{
		cout<<"this is a test func"<<endl;
		cout<<"age = "<<age<<endl<<"name = "<<name<<endl;
	}

	
	


	


private: 
	int age;
	char *name;
};



void main()
{
	//悟空真身
	Wukong *wk = new Wukong(18,"孙悟空");
	wk->Display();

	//分身1
	Wukong *wk1 = (Wukong*)wk->Clone();
	wk1->Display();

	//分身2
	Wukong *wk2 = (Wukong*)wk->Clone();
	wk2->Display();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值