设计模式: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;
}

  

猜你喜欢

转载自www.cnblogs.com/chusiyong/p/11433120.html
今日推荐