原型模式的定義:用原型實例指定創(chuàng)建對象的種類,并且通過拷貝這些原型創(chuàng)建新的對象。
UML圖:

C++代碼:
//filename: prototype.h
//author: Qinglong.mark.He
#include <iostream>
#include <string>
class Prototype
{
protected:
std::string name;
public:
Prototype(){}
virtual ~Prototype(){}
virtual Prototype *clone(){return nullptr;}
virtual void set(char *n){}
virtual void show(){}
};
class PrototypeA: public Prototype
{
public:
PrototypeA(){
name = "PrototypeA";
}
PrototypeA(const PrototypeA &r){
name = r.name;
}
~PrototypeA(){
}
PrototypeA *clone(){
return new PrototypeA(*this);
}
void show(){
std::cout<<"PrototypeA name: "<<name<<std::endl;
}
};
class PrototypeB: public Prototype
{
public:
PrototypeB(){
name = "PrototypeB";
}
PrototypeB(const PrototypeB &r){
name = r.name;
}
~PrototypeB(){
}
PrototypeB *clone(){
return new PrototypeB(*this);
}
void show(){
std::cout<<"PrototypeB name: "<<name<<std::endl;
}
};
測試用例:
#include "prototype.h"
int main(){
auto r1 = new PrototypeA;
auto r2 = new PrototypeB;
auto r3 = r1->clone();
auto r4 = r2->clone();
r1->show();
r2->show();
delete r1;
delete r2;
r3->show();
r4->show();
delete r3;
delete r4;
return 0;
}