The intent of the prototype pattern is to specify the type of object to create with the prototype instance, and to create a new object by copying the prototypes.
Applicability
when the class being instantiated is specified at run time, for example, by dynamic loading;
To avoid creating a factory class level that is parallel to the product class hierarchy;
When an instance of a class can have only one of several different state combinations. Creating a corresponding number of prototypes and cloning them may be more convenient than manually instantiating the class each time with the appropriate state.
About this model, suddenly thought of as a child to see the "Journey to the World", Qi Tian San Wukong again when you can through their head 3 hair immediately copied out thousands of Monkey King, dealing with the small monster is very useful (number of most important).
Prototyping also provides the ability to replicate itself, meaning that the creation of new objects can be created by existing objects. Copying constructors in C + + (copy constructor) was a nightmare for programmers, and the smile of shallow copies and deep copies was one of the root causes of many programmers ' fast food and system crashes during an interview.
Structure Chart:
The prototype pattern provides an interface (clone) that creates a new object from an existing object, and the clone () implementation is related to the specific implementation language, which we will implement in C + + by copying the constructor function.
Example
Precautions:
(1) According to the prototype model of the UML diagram can know that the implementation depends on the abstraction to rely on and specific
(2) Copy constructor is the core, and for C + + to do is a deep copy
(3) The key to cloning a function is to invoke the copy constructor
#include <iostream> using namespace std;
Class Student {Protected:int id;
Char name[10];
Public:student () {} ~student () {cout<< "desconstuct ..." <<endl;
Virtual Student *clone () {} virtual void Show () {}};
Class Studenttypea:public Student {public:studenttypea (const char *name_input) {strcpy (name, name_input);
This->id = 0;
cout<< "Construction ..." <<endl;
} studenttypea (const studenttypea&other) {cout<< "Copy construction ..." <<endl;
This->id = other.id;
This->id + +;
strcpy (This->name, other.name);
Virtual Studenttypea *clone () {Studenttypea *tmp = new Studenttypea (*this);
return TMP;
} void Show () {cout<< "Student id = =" << id << "name = =" << name <<endl; } ~studenttypea () {cout<< "Deconstruction Studenttypea" <<endl;
}
};
int main () {Student *student1 = new Studenttypea ("Fulima");
Student *student2 = Student1->clone ();
Student *student3 = Student2->clone ();
Student1->show ();
Student2->show ();
Student3->show ();
return 0;
}