C++_解析设计模式中的Prototype原型模式及在C++中的使用,原型模式的意图是用原型实例
原型模式的意图是用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
适用性
当要实例化的类是在运行时刻指定时,例如,通过动态装载;或者
为了避免创建一个与产品类层次平行的工厂类层次时;或者
当一个类的实例只能有几个不同状态组合中的一种时。建立相应数目的原型并克隆它们可能比每次用合适的状态手工实例化该类更方便一些。
关于这个模式,突然想到了小时候看的《西游记》,齐天大圣孙悟空再发飙的时候可以通过自己头上的 3 根毛立马复制出来成千上万的孙悟空,对付小妖怪很管用(数量最重要)。
原型模式也正是提供了自我复制的功能,就是说新对象的创建可以通过已有对象进行创建。在 C++中拷贝构造函数(Copy Constructor)曾经是很对程序员的噩梦,浅层拷贝和深层拷贝的魔魇也是很多程序员在面试时候的快餐和系统崩溃时候的根源之一。
结构图:
原型模式提供了一个通过已存在对象进行新对象创建的接口(Clone),Clone()实现和具体的实现语言相关,在 C++中我们将通过拷贝构造函数实现之。
例子
注意事项:
(1)根据原型模式的UML图可以知道,实现要依赖于抽象要不要依赖与具体
(2)拷贝构造函数是核心,而且针对c++要进行的是深拷贝
(3)克隆函数的关键就是调用拷贝构造函数
#include <iostream> using namespace std; class Student { protected: int id; char name[10]; public: Student() { } ~Student() { cout<<"Desconstuct...."<<endl; } virtual Student *Clone() {} virtual void Show() { } }; class StudentTypeA:public Student { public: StudentTypeA(const char *name_input) { strcpy(name, name_input); this->id = 0; cout<<"Construction....."<<endl; } StudentTypeA(const StudentTypeA&other) { cout<<"Copy Construction..."<<endl; this->id = other.id; this->id ++; strcpy(this->name, other.name); } virtual StudentTypeA *Clone() { StudentTypeA *tmp = new StudentTypeA(*this); return tmp; } void Show() { cout<<"Student id == "<< id << " name == "<< name <<endl; } ~StudentTypeA() { cout<<"Deconstruction StudentTypeA"<<endl; } }; int main() { Student *student1 = new StudentTypeA("fulima"); Student *student2 = student1->Clone(); Student *student3 = student2->Clone(); student1->Show(); student2->Show(); student3->Show(); return 0; }
相关热词:
本站内容来源于网络,如有侵权请与我们联系,我们会及时删除,我们深感抱歉!
注:本站所有信息仅供用于网络技术学习参考,学习中请遵循相关法律法规!
本文地址: https://v30.fanwenzhu.com/jiaob/cjj/11564.shtml
相关文章
热门TAG
win10 ecshop 主机 阿里云 解决 配置 C# C++ 解析 SQL语句 命令 Go语言 方法 CSS3 HTML5 CSS win7 MSSQL 服务器配置 IIS7.5 IIS7 IIS6 IIS CentOS 7 Linux oracle数据库 oracle phpcms discuz discuz教程最新文章
-
只需要在调用Ctrl+B编译后
时间:2021-01-13
-
OpenGL超级宝典visual studio
时间:2021-01-04
-
Directx11 教程(2) 基本的wi
时间:2021-01-04
-
LeetCode11ContainerWithMostWate
时间:2021-01-04
-
C语言简单IT之家速成
时间:2020-12-27
-
三分钟了解Activity工作流
时间:2020-12-27
-
编译器是如何实现32位整型
时间:2020-12-27
-
C++中lower_bound函数和upper
时间:2020-12-27
热门文章
-
LeetCode11ContainerWithMostWater(最大水容器)
时间:2021-01-04
-
C语言简单编程速成
时间:2020-12-23
-
都2020了,这五个最佳C++的IDE你还没用过?
时间:2020-12-23
-
C语言源程序文件的后缀是什么?
时间:2020-12-23
-
OpenGL超级宝典visual studio 2013开发环境配置
时间:2021-01-04
-
编译器是如何实现32位整型的常量整数除
时间:2020-12-27
-
libusbwin32学习笔记(二)
时间:2020-12-27
-
C语言简单IT之家速成
时间:2020-12-27
-
C语言和Python语言有什么区别呢?
时间:2020-12-24
-
C++对象模型之RTTI的实现原理
时间:2020-12-23
