07.原型模式--Prototype

 

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

Prototype模式典型的结构图为:
 

07.原型模式--Prototype_第1张图片
以《大话设计模式》中复制简历为实例,下面是Prototype模式的实现代码:

//Prototype.h
#ifndef _PROTOTYPE_H_
#define _PROTOTYPE_H_

#include <string>
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 <iostream>
using namespace std;

Resume::Resume()
{
}

Resume::~Resume()
{
}

Resume* Resume::Clone() const
{
 return 0;
}

BigBirdResume::BigBirdResume(string strName)
{
 m_strName = strName;
 cout<<"BigBirdResume..."<<m_strName<<"的简历"<<endl;
}

BigBirdResume::~BigBirdResume()
{
}

void BigBirdResume::SetExperices(string strTimeArea, string strCompany)
{
 m_strTimeArea = strTimeArea;
 m_strCompany = strCompany;
}

void BigBirdResume::DispExperices()
{
 cout << "姓名: " << m_strName << ", 工作时间: " << m_strTimeArea << ", 公司名称: " << m_strCompany << endl;
}

BigBirdResume::BigBirdResume(const BigBirdResume& cp)
{
 this->m_strName = cp.m_strName;
 this->m_strTimeArea = cp.m_strTimeArea;
 this->m_strCompany = cp.m_strCompany;

 cout<<"BigBirdResume copy ...大鸟的简历"<<endl;
}

Resume* BigBirdResume::Clone() const
{
 return new BigBirdResume(*this);
}


//main.cpp
#include "Prototype.h"
#include <iostream>
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模式重在从自身复制自己创建新类。

你可能感兴趣的:(07.原型模式--Prototype)