通過一個已有對象創(chuàng)建新對象缩麸,這里拷貝構(gòu)造函數(shù)
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