The prototype mode allows you to dynamically create instances of the current actual type through the base class pointer, and quickly copy the current copy.
Prototype. H Content
1 #ifndef Prototype_H_H 2 #define Prototype_H_H 3 4 #include <iostream> 5 using namespace std; 6 7 class Person 8 { 9 public:10 virtual Person* clone() = 0;11 virtual ~Person() {}12 virtual void display() = 0;13 };14 15 class Teacher : public Person16 {17 public:18 virtual Person* clone() { return new Teacher; }19 virtual void display() { cout << "This is a teacher!" << endl; }20 };21 22 class Worker : public Person23 {24 public:25 virtual Person* clone() { return new Worker; }26 virtual void display() { cout << "This is a worker!" << endl; }27 };28 29 30 void PrototypeTest()31 {32 Person *person1 = new Teacher();33 Person *person2 = new Worker();34 35 person1->clone()->display();36 person2->clone()->display();37 38 delete person1;39 delete person2;40 }41 42 #endif
Running result:
Design Pattern 6-prototype Pattern