Design Patterns: prototype mode

Usage scenarios: When you can not create objects based on class, create objects based on existing objects

You can not create an object based on the class of situations:

  • When you create a class object, according to the need to create a variety of objects to create very complex process
  • It is difficult to generate objects from classes

example:

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

  

Guess you like

Origin www.cnblogs.com/chusiyong/p/11433120.html