原文鏈接:點擊打開鏈接
功能:用原型實例指定創建對象的種類,並通過拷貝這些原型創建新的對象。原型模式其實就是從一個對象創建另外一個可定製的對象,而且不需知道任何創建的細節。
優點:
一般在初始化的信息不發生變化的情況下,克隆是最好的辦法,既隱藏了對象創建細節,又提高性能。其等於是不用重新初始化對象,而是動態地獲得對象運行時的狀態。
缺點:
模式應用:
C++舉例:
#ifndef PROTOTYPE_H
#define PROTOTYPE_H
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
class ProtoType{
private:
string m_strName;
public:
ProtoType(){m_strName="";}
ProtoType(string temp){m_strName=temp;}
void Show(){cout<<m_strName<<endl;}
virtual ProtoType* Clone()=0;
};
class ProtoTypeFirst : public ProtoType{
public:
ProtoTypeFirst(){}
ProtoTypeFirst(string temp): ProtoType(temp){}
virtual ProtoType* Clone(){
ProtoTypeFirst* p=new ProtoTypeFirst;
*p=*this;
return p;
}
};
class ProtoTypeSecond : public ProtoType{
public:
ProtoTypeSecond(){}
ProtoTypeSecond(string temp):ProtoType(temp){}
virtual ProtoType* Clone(){
ProtoTypeSecond* p=new ProtoTypeSecond;
*p=*this;
return p;
}
};
#endif
#include <iostream>
#include "prototype.h"
int main(){
ProtoTypeFirst* pExampleA=new ProtoTypeFirst("James");
ProtoTypeSecond* pExampleB=(ProtoTypeSecond*)pExampleA->Clone();
pExampleA->Show();
pExampleB->Show();
return 0;
}