一、意图:
用原型实例制定创建对象的种类,并且通过拷贝创建新的对象;
二、类图:
三、组成元素:
Prototype:声明克隆自身的接口;
ConcretePrototype:实现克隆自身的操作;
四、实现代码:
#include <iostream> using namespace std; class Prototype { private: int num; char* name; public: virtual Prototype* clone()=0; virtual Prototype* deepclone()=0; virtual void sayHello()=0; }; class ConcretePrototype:public Prototype { private: char* name; int num; public: Prototype* clone() { return new ConcretePrototype(this->name,this->num); } Prototype* deepclone() { <strong> int tempnum; char* tempname=new char[strlen(name)+1]; tempnum=num; strcpy(tempname,name);</strong> return new ConcretePrototype(tempname,tempnum); } void sayHello() { cout<<"ConcrePrototype:"<<this->name<<":"<<this->num<<endl; } ConcretePrototype(char* na,int n) { name=na; num=n; }; }; void main() { Prototype* pPrototype1=new ConcretePrototype("conan",100); Prototype* pPrototype11=pPrototype1->clone(); pPrototype1->sayHello(); pPrototype11->sayHello(); Prototype* pPrototype2=new ConcretePrototype("柯南",200); Prototype* pPrototype22=pPrototype2->deepclone(); pPrototype2->sayHello(); pPrototype22->sayHello(); }
clone:是浅克隆;
deepclone:是深克隆;