您的位置:首页 > 其它

设计模式学习系列6 原型模式(prototype)

2013-11-07 13:38 513 查看
原型模式(prototype)用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。允许一个对象再创建另外一个新对象的时候根本无需知道任何创建细节,只需要请求圆形对象的copy函数皆可。

1原型模式构成





客户(Client)角色:客户类提出创建对象的请求。
抽象原型(Prototype)角色:这是一个抽象角色,C++实现的抽象类,此角色给出所有的具体原型类所需的接口。
具体原型(ConcretePrototype)角色:被复制的对象。此角色需要实现抽象原型角色所要求的接口。

2原型模式C++实现

(1)通过C++的拷贝构造函数实现

(2)clone()函数返回的类是基类,建议通过static_const<>()进行转换为子类

(3)原型模式实现过程中会涉及浅拷贝和深拷贝的问题,clone()编写的时候要注意

(4)原型模式创建新的对象简单了很多,只需要根据原型就可以获得,不过使用原型的时候内存在clone内部开辟,要记得释放


[code]/*设计模式学习系列之原型模式
*参考书籍《大话设计模式》

*通过明确的clone()来创造新对象,不需要知道创建的任何细节

*/

#include<iostream>

usingnamespacestd;

//接口类

classPrototype

{

public:
virtualPrototype*Clone()const=0;

};

structstStruct

{
intnum;
stringstr;
stStruct()
{
num=0;
str="";
}

};

classPrototypeA:publicPrototype

{

protected:
inta;
stringstr;

public:
PrototypeA():a(0)
{
}
~PrototypeA()
{
}
//参数构造函数1
PrototypeA(constint&_a,conststring&_str):a(_a),str(_str)
{
}
//参数构造函数
PrototypeA(constPrototypeA&_proto)
{
a=_proto.a;
str=_proto.str;
}
//clone()函数深拷贝
Prototype*Clone()const
{
PrototypeA*P=newPrototypeA(*this);
returnP;
}
voidshow()
{
cout<<a<<"---"<<str<<endl;
}
voidSetA(constint&_a)
{
a=_a;
}
voidSetStr(conststring&_str)
{
str=_str;
}

};

intmain()

{
PrototypeA*test=newPrototypeA(1,"xxxx");
//通过clone()创建
PrototypeA*test_clone=static_cast<PrototypeA*>(test->Clone());
//通过拷贝构造函数创建
PrototypeA*test2=newPrototypeA(*test);
cout<<"===============赋值结束"<<endl;
test->show();
test_clone->show();
test2->show();
cout<<"===============修改值类型"<<endl;
test->SetA(3);
test->show();
test_clone->show();
test2->show();
cout<<"===============修改字符类型"<<endl;
test->SetStr("343245");
test->show();
test_clone->show();
test2->show();

}

[/code]

3涉及到的C++知识点

(1)c++深拷贝和浅拷贝http://www.2cto.com/kf/201205/133802.html

(2)C++类拷贝赋值构造函数http://blog.chinaunix.net/uid-25808509-id-354211.html


细雨淅淅标签:设计模式
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: