DesignPatterns_Prototype

///
// Prototype Pattern
// - Specify the kinds of objects to create using a prototypical 
//   instance, and create new object by copying this prototype.
//
// Author  : ZAsia
// Data    : 15/05/06
// Warning : In practice, declaration and implementation should be 
//           separated(in .h and .cpp).
///

// Prototype
// - declares an interface for cloning itself
class Prototype
{
public:
	virtual Prototype *Clone() = 0;
};

// ConcretePrototype
// - implements an operation for cloning itself
class ConcretePrototype : public Prototype
{
public:
	// default constructor
	ConcretePrototype() : m_iAttributes(0) { }

	// copy constructor
	ConcretePrototype(const ConcretePrototype &orig) 
	{ 
		m_iAttributes = orig.m_iAttributes;
	}

	// clone
	virtual Prototype *Clone() { return new ConcretePrototype(*this); }

private:
	int m_iAttributes;
};

// Client
// - creates a new object by asking a prototype to clone itself
int main()
{
	Prototype *pConProA = new ConcretePrototype();
	// ask a prototype to clone itself
	Prototype *pConProB = pConProA->Clone();

	if (pConProA != nullptr) { delete pConProA; pConProA = nullptr; }
	if (pConProB != nullptr) { delete pConProB; pConProB = nullptr; }

	return 0;
}

// Implementation
// - Implementing the Clone operation. 
//   The default copy constructor in C++ does a memberwise copy, which means
//   pointers will be shared between the copy and the original. But cloning 
//   prototypes with complex structures usually requires a depp copy, because
//   the clone and the original must be independent. 
// - Initializing clones.
//   While some clients are perfectly happy with the clone as is, others will
//   want to initialize some or all of its internal state to values of their
//   choosing. Passing parameters in the Clone operation precludes a uniform 
//   cloning interface.
//   You may introduce an Initialize operation that takes initialization
//   parametersas argument and sets the clone's internal state accordingly. 
//   Beware of deep-copying Clone operations--the copies may have to be deleted
//   (either explicitly or within Initialize)before you reinitialize them.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值