设计模式学习系列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]/*设计模式学习系列之原型模式
[/code]
3涉及到的C++知识点
(1)c++深拷贝和浅拷贝http://www.2cto.com/kf/201205/133802.html
(2)C++类拷贝赋值构造函数http://blog.chinaunix.net/uid-25808509-id-354211.html
细雨淅淅标签:设计模式
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++深拷贝和浅拷贝
(2)C++类拷贝赋值构造函数
细雨淅淅标签:
相关文章推荐
- 设计模式系列学习四:原型模式(Prototype)
- 设计模式学习之--原型模式(Prototype)
- 小菜学习设计模式(四)—原型(Prototype)模式
- 设计模式学习笔记--Prototype原型模式
- 设计模式学习之--PROTOTYPE(原型)对象创建型模型
- 设计模式学习笔记---原型模式prototype(Java版)
- 设计模式学习之原型模式(Prototype)
- 学习php设计模式 php实现原型模式(prototype)
- 设计模式深入学习---Prototype原型模式
- php设计模式学习系列(七)--原型对象
- 设计模式学习笔记--工厂(Factory)、建造(Builder)和原型(Prototype)
- 步步为营 .NET 设计模式学习笔记 五、Prototype(原型模式)
- 步步为营 .NET 设计模式学习笔记 五、Prototype(原型模式)
- 【HeadFirst 设计模式学习笔记】18 原型(Prototype)模式拾零
- 设计模式学习系列之原型模式
- 从FLC中学习的设计模式系列-创建型模式(5)-原型
- 设计模式学习----Prototype原型模式
- 菜鸟学设计模式系列笔记之Prototype模式(原型模式)
- 【设计模式学习笔记五】【创建型模式】【原型模式(Prototype)】
- 设计模式学习总结4 - 创建型4 - Prototype原型模式