Design Pattern 6-prototype Pattern

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.