原型模式优点:
从一个对象再创建另外一个可定制的对象,而无需知道任何创建的细节。并能提高创建的性能。 说白了就 COPY 技术,把一个对象完整的 COPY 出一份。
下面是代码:
#include
#include
#include
using namespace std;
//抽象类
class ProtoType
{
private:
string m_strName;
public:
ProtoType(string strName)
{
m_strName = strName;
}
ProtoType(){m_strName = "";}
virtual void Show()
{
cout << m_strName << endl;
}
virtual ProtoType* Clone() = 0;
};
//要克隆的之类ConcretePrototype1
class ConcretePrototype1 : public ProtoType
{
public:
ConcretePrototype1(string strName) : ProtoType(strName){}
ConcretePrototype1(){}
virtual ProtoType* Clone()
{
ConcretePrototype1* p = new ConcretePrototype1();
*p = *this; //复制对象
return p;
}
};
//要克隆的之类ConcretePrototype2
class ConcretePrototype2 : public ProtoType
{
public:
ConcretePrototype2(string strName) : ProtoType(strName){}
ConcretePrototype2(){}
virtual ProtoType* Clone()
{
ConcretePrototype2* p = new ConcretePrototype2();
*p = *this; //复制对象
return p;
}
};
//客户端
int main()
{
ConcretePrototype1* test = new ConcretePrototype1("小王");
ConcretePrototype2* test2 = (ConcretePrototype2*)test->Clone();
test->Show();
test2->Show();
return 0;
}
阅读(1209) | 评论(1) | 转发(0) |