///
// 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.
DesignPatterns_Prototype
最新推荐文章于 2021-12-29 22:15:08 发布