设计模式C++版:第十七式原型模式

原型其实就是从一个对象再创建另一个对象,且不需要知道细节。如果使用原型模式,要保持灵活性,接口应该尽量丰富

例如:起始每个接口只影响一个属性,然后提供多个单一属性接口组合成的多属性接口。

#include <iostream>
#include <string>
using std::string;
using std::cout; using std::endl;

/*
因为所有的子类,即原型要使用到父类类型,ProtoType*,
所有接口还是不能够纯虚,即父类不能是抽象类。
*/
class ProtoType                                
{
public:
	ProtoType(int age ) :m_age(age){ }

	virtual void setname(const string &name,int id)
	{
		m_name = name;
		m_id = id;
	}
	virtual void putout()
	{
		cout << "姓名" << m_name << " 年龄" << m_age << "编号" << m_id << endl;
	}

	virtual ProtoType* clone()
	{
		return this;
	}
protected:
	int m_id;
	int m_age;
	string m_name;
};

class ConcreteType1 :public ProtoType
{
public:
	ConcreteType1(int age) :ProtoType(age)
	{
		
	}

	virtual void setname(const string &name ,int id)override
	{
		m_name = name;
		m_id = id;
	}

	void putout()
	{
		cout << "ConcreteType1 : " << "姓名" << m_name << " 年龄" << m_age << "编号" << m_id << endl;
	}
};


class ConcreteType2 :public ProtoType
{
public:
	/*调用父类构造函数,传参id,然后初始化自身。也就是拷贝了父类成员*/
	ConcreteType2(int age) :ProtoType(age) 
	{
	
	}

	virtual void setname(const string &name,int id)override
	{
		m_id = id;
		m_name = name;
	}

	void putout()
	{
		cout << "ConcreteType2 : " << "姓名" << m_name << " 年龄" << m_age << "编号" << m_id << endl;
	}
};


int  main()
{
	/*原型*/
	ConcreteType1 *type1 = new ConcreteType1(27);
	type1->setname("张三",1101);

	//新对象1
	ConcreteType1 type1_2 = *(ConcreteType1*)type1->clone();   //拷贝整个对象
	type1_2.setname("李四",1102);

	//新对象2
	ConcreteType2 type2_1 = *(ConcreteType2*)type1->clone();   //拷贝整个对象
	type2_1.setname("王五", 1103);

	type1->putout();
	type1_2.putout();
	type2_1.putout();

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值