I. Overview
Definition: You can use a prototype instance to specify the object type and copy the prototype to create a new object.
In other words, you do not need to reinitialize the object, but dynamically obtain the status of the object during running.
To be clear, we need an interface that has copied similar features of the constructor.
The structure is as follows:
The Code is as follows:
[Cpp] // prototype class, with a clone Interface
Class Prototype
{
Public:
Virtual ~ Prototype (){}
Virtual Prototype * Clone () const = 0;
};
// A specific prototype class for clone operations
Class ConcretePrototype: public Prototype
{
Public:
ConcretePrototype (){}
// Copy the constructor
ConcretePrototype (const ConcretePrototype & cp)
{
Cout <"ConcretePrototype copy..." <endl;
}
// Clone Interface
Prototype * Clone () const
{
Return new ConcretePrototype (* this );
}
};
// Test code
Int main (int argc, char * argv [])
{
// Copy the constructor
ConcretePrototype p1;
ConcretePrototype p2 = p1;
// Clone www.2cto.com
Prototype * p3 = new ConcretePrototype ();
Prototype * p4 = p3-> Clone ();
Return 0;
}
// Prototype class, with a clone Interface
Class Prototype
{
Public:
Virtual ~ Prototype (){}
Virtual Prototype * Clone () const = 0;
};
// A specific prototype class for clone operations
Class ConcretePrototype: public Prototype
{
Public:
ConcretePrototype (){}
// Copy the constructor
ConcretePrototype (const ConcretePrototype & cp)
{
Cout <"ConcretePrototype copy..." <endl;
}
// Clone Interface
Prototype * Clone () const
{
Return new ConcretePrototype (* this );
}
};
// Test code
Int main (int argc, char * argv [])
{
// Copy the constructor
ConcretePrototype p1;
ConcretePrototype p2 = p1;
// Clone
Prototype * p3 = new ConcretePrototype ();
Prototype * p4 = p3-> Clone ();
Return 0;
}
Ii. Description
1. The key to Prototype mode is the implementation of copying constructor in C ++, which is also a technical aspect of C ++ implementation.
2. The sample code does not involve deep copy (mainly in the case of pointers and composite objects), but mainly reflects the idea of Prototype mode.
Author lwbeyond