原型模式主要指通过基类的指针能够动态创建出当前实际类型的实例,可以快速复制出当前的一个副本。
Prototype.h内容
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 Person 16 { 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 Person 23 { 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
运行结果:
时间: 2024-12-28 21:40:37