博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
07.原型模式--Prototype
阅读量:2393 次
发布时间:2019-05-10

本文共 1956 字,大约阅读时间需要 6 分钟。

原文地址:

Prototype模式:

Prototype模式用于指定创建对象的种类,并且通过拷贝这些原型创建新的对象。也就是说从一个对象再创建另外一个可以定制的对象,而且不需要知道任何创建的细节。
它提供了一个通过已存在对象进行新对象创建的接口(Clone),Clone()实现和具体的实现语言相关,在C++中我们将通过拷贝构造函数实现之。
一般在初始化的信息部发生变化的情况下,克隆是最好的办法,它隐藏了对象创建的细节,又能提高性能。不用重新初始化对象,而是动态的获得对象运行时的状态。
Prototype模式的结构和实现都很简单,其关键就是(C++中)拷贝构造函数的实现方式。

Prototype模式典型的结构图为:

 

以《大话设计模式》中复制简历为实例,下面是Prototype模式的实现代码:

//Prototype.h#ifndef _PROTOTYPE_H_#define _PROTOTYPE_H_#include 
using namespace std;// 简历class Resume{public: virtual ~Resume(); virtual Resume* Clone() const = 0; virtual void SetExperices(string strTimeArea, string strCompany) = 0; virtual void DispExperices() = 0;protected: Resume(); string m_strName; string m_strTimeArea; string m_strCompany;private:};// 大鸟的简历class BigBirdResume:public Resume{public: BigBirdResume(string strName); BigBirdResume(const BigBirdResume& cp); ~BigBirdResume(); Resume* Clone() const; virtual void SetExperices(string strTimeArea, string strCompany); virtual void DispExperices();protected:private:};#endif //~_PROTOTYPE_H_//Prototype.cpp#include "Prototype.h"#include
using namespace std;Resume::Resume(){}Resume::~Resume(){}Resume* Resume::Clone() const{ return 0;}BigBirdResume::BigBirdResume(string strName){ m_strName = strName; cout<<"BigBirdResume..."<
<<"的简历"<
m_strName = cp.m_strName; this->m_strTimeArea = cp.m_strTimeArea; this->m_strCompany = cp.m_strCompany; cout<<"BigBirdResume copy ...大鸟的简历"<
using namespace std;int main(int argc,char* argv[]){ Resume* p = new BigBirdResume("大鸟"); p->SetExperices("2000", "皮包公司"); p->DispExperices(); Resume* p1 = p->Clone(); p1->SetExperices("2011", "草包公司"); p1->DispExperices(); return 0;}
Prototype模式通过复制原型(Prototype)而获得新对象创建的功能,这里Prototype本身就是“对象工厂”(因为能够生产对象),实际上Prototype模式和Builder模式、AbstractFactory模式都是通过一个类(对象实例)来专门负责对象的创建工作(工厂对象),它们之间的区别是:
Builder模式重在复杂对象的一步步创建(并不直接返回对象)。
AbstractFactory模式重在产生多个相互依赖类的对象。
Prototype模式重在从自身复制自己创建新类。

你可能感兴趣的文章
网络性能测试工具Iperf上手指南
查看>>
opensecuritytraining video
查看>>
collective intelligence framework
查看>>
2015年关注的技术书籍
查看>>
windows 2003 server 记录远程桌面的连接登录日志和修改3389连接端口方法
查看>>
samhain:比较变态的入侵检测系统
查看>>
Linux psacct文档
查看>>
使用setuptools自动安装python模块
查看>>
python IDE环境
查看>>
传说中的windows加固 -.... -
查看>>
windows目录监控软件
查看>>
Virus Bulletin malware分析杂志以及paper
查看>>
Security Considerations for AppLocker
查看>>
Oracle Forensics t00ls
查看>>
zZ-ModSecurity Framework支持Web应用安全核心规则集
查看>>
apache 防DDOS脚本
查看>>
使用syslog-ng 和stunnel 创建集中式安全日志服务器
查看>>
网友将电视剧潜伏当职场教科书 研究办公室政治
查看>>
graudit
查看>>
使用Hudson和FindBugs进行持续集成和代码检查
查看>>