设计模式之原型模式

来源:互联网 发布:并购发展前景 知乎 编辑:程序博客网 时间:2024/06/05 09:41

创建型模式就剩下最后一种原型模式了

定义:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象

看这个字面意思就是去拷贝对象,复制对象,原型模式其实就是从一个对象再创建另外一个可定制的对象,而且不需要知道任何创建

的细节

在我们找工作的时候我们基本上都是制作一份简历,然后打印多份去投递,但是由于我们投递的岗位不同,简历上有些东西还是有些

不一样的,比如求职岗位,下面我们就以这个例子写一写代码吧

#include<iostream>#include<string>using namespace std;class Resume{private:string m_name;string m_jobname;string m_tel;string m_address;string m_email;public://因为除了岗位以外,其他的都是一样的,我们就可以在构造函数中初始化它们Resume(string name, string tel, string address, string email):m_name(name), m_tel(tel), m_address(address), m_email(email){}void setJobName(string jobname){m_jobname = jobname;}string getJobName(){return this->m_jobname;}virtual Resume* clone() = 0;void show(){cout << "  姓 名 :" << this->m_name << endl;cout << "求职目标:" << this->m_jobname << endl;cout << "电话号码:" << this->m_tel << endl;cout << "家庭住址:" << this->m_address << endl;cout << "电子邮箱:" << this->m_email << endl;}};class ResumeA :public Resume{public:ResumeA(string name, string tel, string address, string email):Resume(name,tel,address,email){}Resume* clone(){return new ResumeA(*this);}};int main(void){Resume* resume = new ResumeA("张三","18792574062","地球上","123456789@qq.com");resume->setJobName("软件开发");resume->show();Resume* resume1 = resume->clone();resume1->setJobName("测试开发");resume1->show();return 0;}
下来我们看一看原型模式的具体代码吧
class Prototype{private:string id;public:void setId(string id){this->id = id;}string getId(){return id;}virtual Prototype* clone() = 0;};class ConcretePrototype :public Prototype{public:Prototype* clone(){return new ConcretePrototype();}};int main(void){Prototype* protype1 = new ConcretePrototype();protype1->setId("123");cout << protype1->getId() << endl;Prototype* protype2 = protype1->clone();protype2->setId("456");cout << protype2->getId() << endl;return 0;}
适用情况:

1、当实例化的类是在运行时指定

2、为了避免创建一个与产品类层次平行的工厂类层次时

3、当一个类的实例只要几种不同状态组合中的一种时

优点:快速且准确的复制一个对象

缺点:当类的构造函数比较复杂时,会影响性能


原创粉丝点击