概念
原型模式:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
原理:利用一个Clone函数来封装了自身的拷贝构造函数,调用Clone函数时就会触发拷贝构造。
使用场景
利用已有的一个原型对象,快速地生成和原型对象一样的实例
一般步骤
1.设计一个接口类,这步感觉可有可无;
class ICloneable { public: virtual ICloneable *Clone()=0; };
2.写一个类用来继承前面的接口类,并实现克隆方法,如果需要深拷贝的话,需要自己实现拷贝构造函数;
关于拷贝构造函数,或者浅拷贝、深拷贝有不清楚的可以看这《C++入门知识-拷贝构造函数-浅拷贝、深拷贝》
class Resume : public ICloneable // 简历类 { private: string name; // 名字 string sex; // 性别 string age; // 年龄 WorkExperience *work; // 工作 public: #if DEEP_COPY Resume(const Resume &resume) //拷贝构造函数,实现深拷贝 { this->name = resume.name; this->sex = resume.sex; this->age = resume.age; cout<<resume.work->workDate<<" "<<resume.work->workCompany<<endl; this->work = new WorkExperience(); this->work->workDate = resume.work->workDate; this->work->workCompany = resume.work->workCompany; } #endif ICloneable *Clone() { return new Resume(*this); // 关键步骤:调用拷贝构造函数,将当前对象的非静态字段复制到新对象 } };
具体实例完整代码
//06Prototype.cpp #include <iostream> #include <string> using namespace std; #define DEEP_COPY 1 class ICloneable { public: virtual ICloneable *Clone()=0; }; class WorkExperience { public: string workDate; string workCompany; }; class Resume : public ICloneable // 简历类 { private: string name; // 名字 string sex; // 性别 string age; // 年龄 WorkExperience *work; // 工作 public: #if DEEP_COPY Resume(const Resume &resume) //拷贝构造函数,实现深拷贝 { this->name = resume.name; this->sex = resume.sex; this->age = resume.age; cout << resume.work->workDate << " " << resume.work->workCompany << endl; this->work = new WorkExperience(); this->work->workDate = resume.work->workDate; this->work->workCompany = resume.work->workCompany; } #endif Resume(string name) { this->name = name; this->work = new WorkExperience(); } void SetPersonalInfo(string age, string sex) { this->sex = sex; this->age = age; } void SetWorkExperience(string workDate, string workCompany) { this->work->workDate = workDate; this->work->workCompany = workCompany; } void Display() { cout << name << " " << sex << " " << age << endl; cout << work->workDate << " " << work->workCompany << endl; cout << &work->workDate << " " << &work->workCompany << endl; } ICloneable *Clone() { // 关键步骤:调用拷贝构造函数,将当前对象的非静态字段复制到新对象 return new Resume(*this); } }; int main() { Resume *a = new Resume("大鸟"); a->SetPersonalInfo("男","29"); a->SetWorkExperience("1998-2000","XX公司"); a->Display(); Resume *b = (Resume *)a->Clone(); b->Display(); // 其实按照下面这种调用也会触发拷贝构造函数,效果和这个模式一样 Resume *c = a; c->Display(); return 0; }
参考资料
程杰老师的《大话设计模式》
C++设计模式——原型模式(Prototype Pattern)
如果对你有帮助的话,记得点赞、收藏,如果有什么遗漏的或者有什么体会,请在评论告诉我,好东西记得分享 ^ _ ^