作用:
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
Prototype模式提供了一个通过已存在对象进行新对象创建的接口(Clone), Clone()实现和具体的语言相关,在C++中通过拷贝构造函数实现。
代码如下:
#pragma once
#include<iostream>
using namespace std;
class Prototype
{
public:
virtual ~Prototype()
{
}
virtual Prototype* Clone() = 0;
protected:
Prototype()
{
}
};
class ConcretePrototype1:public Prototype
{
public:
ConcretePrototype1()
{
cout<<"~ConcretePrototype1"<<endl;
}
~ ConcretePrototype1()
{
}
ConcretePrototype1(const ConcretePrototype1& pConPt)
{
cout<<"ConcretePrototype1 copy"<<endl;
}
virtual Prototype* Clone()
{
return new ConcretePrototype1(*this);
}
private:
};
class ConcretePrototype2:public Prototype
{
public:
ConcretePrototype2()
{
cout<<"~ConcretePrototype2"<<endl;
}
~ ConcretePrototype2()
{
}
ConcretePrototype2(const ConcretePrototype2& pConPt)
{
cout<<"ConcretePrototype2 copy"<<endl;
}
virtual Prototype* Clone()
{
return new ConcretePrototype2(*this);
}
private:
};
client :
// PrototypeMode.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include"Prototype.hpp"
int _tmain(int argc, _TCHAR* argv[])
{
Prototype *p1 = new ConcretePrototype1();
Prototype *p2= p1->Clone();
Prototype *p3 = new ConcretePrototype2();
Prototype *p4= p3->Clone();
system("pause");
return 0;
}
本文介绍了Prototype设计模式的概念及其在C++中的实现方式。该模式通过复制已有对象来创建新对象,避免了创建过程中的复杂初始化步骤。文章提供了具体的代码示例,展示了如何使用Prototype模式创建不同类型的对象。
&spm=1001.2101.3001.5002&articleId=53103878&d=1&t=3&u=d7c9c03f6bd04f60a484d0e123ff970f)
2187

被折叠的 条评论
为什么被折叠?



