意圖:
用原型實例指定創建對象的種類,並且通過拷貝這些原型創建新的對象。
適用性:
當一個系統應該獨立於他的產品創建、構成和表示時,需要使用原型模式
當要實例化的類是在運行時刻指定時,如通過動態裝載
爲了避免創建一個與產品類層次平行的工廠類層次時
當一個類的實例只能有幾個不同狀態組合中的一種時,建立相應數目的原型並克隆他們可能比每次用合適的狀態手工實例化該類更方便一些。
1、
#ifndef _PATTERNPROTOTYPE_H_
#define _PATTERNPROTOTYPE_H_
#include <iostream>
using namespace std;
class Prototype
{
protected :
int age;
public :
Prototype(){}
virtual ~Prototype(){}
//純虛函數,需要供繼承者自行實現
virtual Prototype * clone()=0;
void setAge(int age)
{
this->age=age;
}
int getAge()
{
return age;
}
};
class PrototypeOne:public Prototype
{
public :
PrototypeOne()
{
cout<<"Prototype create"<<endl;
}
PrototypeOne(PrototypeOne & one)
{
cout<<"copy the PrototypeOne"<<endl;
}
virtual ~ PrototypeOne()
{
cout<<"destruction of PrototypeOne"<<endl;
}
virtual Prototype * clone()
{
return new PrototypeOne(*this);
}
};
#endif
2、
#include <iostream>
#include <string>
#include "PatternPrototype.h"
using namespace std;
int main()
{
Prototype *prototype=new PrototypeOne();
Prototype *copytype1 = prototype->clone();
cout<<prototype->getAge()<<endl;
cout<<copytype1->getAge()<<endl;
prototype->setAge(200);
copytype1->setAge(100);
cout<<prototype->getAge()<<endl;
cout<<copytype1->getAge()<<endl;
delete prototype;
delete copytype1;
system("pause");
return 0;
}