设计模式:prototype模式

本文介绍了一种在无法直接通过类创建对象的情况下,利用已有对象进行复制的原型模式实现方法。通过具体的代码示例展示了如何创建一个可以复制自身的产品类。

使用场景:在不能根据类创建对象的时候,根据已有的对象创建对象

不能根据类创建对象的情况:

  • 创建一个类的对象时,需要根据多种对象来创建,创建的过程非常复杂
  • 难以根据类生成对象

例子:

class Product
{
public:
	virtual Product* createClone() = 0;
	virtual void use() = 0;
};
class Apple: public Product
{
	int x;
public:
	Product* createClone()
	{
		return new Apple(*this);
	}
	
	Apple(int x = 0)
	{
		this->x = x;
	}
	
	Apple(const Apple& other)
	{
		x = other.x;
	}
	
	void use()
	{
		cout << "x = " << x << endl;
	}
};
int main() 
{
	Product* p1 = new Apple(10);
	Product* p2 = p1->createClone();
	
	p1->use();
	p2->use();
	
	return 0;
}

  

转载于:https://www.cnblogs.com/chusiyong/p/11433120.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值