本文共 1956 字,大约阅读时间需要 6 分钟。
原文地址:
Prototype模式: Prototype模式用于指定创建对象的种类,并且通过拷贝这些原型创建新的对象。也就是说从一个对象再创建另外一个可以定制的对象,而且不需要知道任何创建的细节。 它提供了一个通过已存在对象进行新对象创建的接口(Clone),Clone()实现和具体的实现语言相关,在C++中我们将通过拷贝构造函数实现之。 一般在初始化的信息部发生变化的情况下,克隆是最好的办法,它隐藏了对象创建的细节,又能提高性能。不用重新初始化对象,而是动态的获得对象运行时的状态。 Prototype模式的结构和实现都很简单,其关键就是(C++中)拷贝构造函数的实现方式。
Prototype模式典型的结构图为:
以《大话设计模式》中复制简历为实例,下面是Prototype模式的实现代码:
//Prototype.h#ifndef _PROTOTYPE_H_#define _PROTOTYPE_H_#includePrototype模式通过复制原型(Prototype)而获得新对象创建的功能,这里Prototype本身就是“对象工厂”(因为能够生产对象),实际上Prototype模式和Builder模式、AbstractFactory模式都是通过一个类(对象实例)来专门负责对象的创建工作(工厂对象),它们之间的区别是: Builder模式重在复杂对象的一步步创建(并不直接返回对象)。 AbstractFactory模式重在产生多个相互依赖类的对象。 Prototype模式重在从自身复制自己创建新类。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;}