标签:
原型模式
目的:
Specify the kinds of objects to create using a prototypical instance, and create
new objects by copying this prototype.
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
C++实现要点:
//Prototype.h #include <string> using namespace std; class Prototype { public: virtual Prototype *clone()=0; virtual void show()=0; }; class concretePrototype1:public Prototype { private: string m_str; public: concretePrototype1(); concretePrototype1(string cstr); concretePrototype1(const concretePrototype1 &c); virtual Prototype *clone(); virtual void show(); }; class concretePrototype2:public Prototype { private: string m_str; public: concretePrototype2(string cstr); concretePrototype2(const concretePrototype2 &c); virtual Prototype *clone(); virtual void show(); }; //Prototype.cpp #include "Prototype.h" #include <iostream> /* using namespace std; concretePrototype1::concretePrototype1() { cout<<"default the concretePrototype1"<<endl; this->m_str="default type1"; } concretePrototype1::concretePrototype1(string cstr) { cout<<"construct the concretePrototype1"<<endl; this->m_str=cstr; } concretePrototype1::concretePrototype1(const concretePrototype1 &c) { cout<<"copy the concretePrototype1"<<endl; this->m_str=c.m_str; } Prototype *concretePrototype1::clone() { cout<<"clone the concretePrototype1"<<endl; return new concretePrototype1(*this); } void concretePrototype1::show() { cout<<"show the concretePrototype1"<<endl; cout<<this->m_str<<endl; } concretePrototype2::concretePrototype2(string cstr) { this->m_str=cstr; } concretePrototype2::concretePrototype2(const concretePrototype2 &c) { cout<<"copy the concretePrototype2"<<endl; this->m_str=c.m_str; } Prototype *concretePrototype2::clone() { return new concretePrototype2(*this); } void concretePrototype2::show() { cout<<this->m_str<<endl; } //main.cpp #include “Prototype.h” void main() { concretePrototype1 cp1; concretePrototype1 cp2=cp1; //原来的调用复制构造函数 cp1.show(); cp2.show(); Prototype *cp3=new concretePrototype1("concretePrototype1"); //指针的类型是父类 cp3->show(); Prototype *cp4=cp3->clone(); cp4->show(); delete cp3; cp3=NULL; cp4->show(); return ; }
参考资料
1 设计模式C++描述----08.原型(Prototype)模式
4 我所理解的设计模式(C++实现)——原型模式(Prototype Pattern)
标签:
原文地址:http://www.cnblogs.com/gjianw217/p/3870698.html