Prototype 模式

时间:2022-12-16 07:01:36

Prototype 模式提供了一个通过已存在对象进行新对象创建的接口(Clone) ,Clone()实现和具体的实现语言相关,在 C++中我们将通过拷贝构造函数实现之。

Prototype 模式

////////////////Prototype.h///////
#ifndef _PROTOTYPE_H_
#define _PROTOTYPE_H_
class Prototype
{
public:
virtual ~Prototype();
virtual Prototype* Clone() const = ;
protected:
Prototype();
private:
}; class ConcretePrototype : public Prototype
{
public:
~ConcretePrototype();
ConcretePrototype();
ConcretePrototype(const ConcretePrototype& cp);
Prototype* Clone() const;
protected:
private:
}; #endif
 ////////////////Prototype.cpp///////
#include "Prototype.h"
#include <iostream>
using namespace std; Prototype::~Prototype()
{ }
Prototype::Prototype()
{ }
Prototype* Prototype::Clone() const
{
return ;
}
ConcretePrototype::~ConcretePrototype()
{ }
ConcretePrototype::ConcretePrototype()
{
cout<<"创建一个对象"<<endl;
}
ConcretePrototype::ConcretePrototype(const ConcretePrototype& cp)
{
cout<<"复制原型"<<endl;
}
Prototype* ConcretePrototype::Clone() const
{
return new ConcretePrototype(*this);
}
 ////////////////main.cpp///////
#include "Prototype.h"
#include <iostream>
using namespace std; int main()
{
Prototype* p = new ConcretePrototype();
Prototype* p1 = p->Clone();
Prototype* p2 = p1->Clone(); system("pause");
return ;
}