通过一个已有对象创建新对象,这里拷贝构造函数
prototype.h
#ifndef _PROTOTYPE_H
#define _PROTOTYPE_H
#include <iostream>
using namespace std;
class Prototype
{
public:
virtual ~Prototype() {};
virtual Prototype* Clone() const = 0;
protected:
Prototype() {};
};
class ConcretePrototype : public Prototype
{
public:
ConcretePrototype() {};
ConcretePrototype(const ConcretePrototype& cp) {
cout << "ConcretePrototype copy" << endl;
}
~ConcretePrototype() {};
Prototype* Clone() const {
return new ConcretePrototype(*this);
}
};
#endif // _PROTOTYPE_H
prototype.cpp
#include "prototype.h"
int main()
{
Prototype* p = new ConcretePrototype;
Prototype* p1 = p->Clone();
return 0;
}
编译:make prototype