适用情境:一个对象复制自身.
// prototype.h
#ifndef PROTOTYPE_H
#define PROTOTYPE_H
class Prototype
{
public:
Prototype();
Prototype(int id);
virtual void Show();
virtual Prototype *Clone() = 0;
private:
int m_iId;
};
#endif // PROTOTYPE_H
// prototype.cpp
#include "prototype.h"
#include <iostream>
Prototype::Prototype()
{
m_iId = 0;
}
Prototype::Prototype(int id)
{
m_iId = id;
}
void Prototype::Show()
{
std::cout << m_iId << std::endl;
}
// concreteprototypea.h
#ifndef CONCRETEPROTOTYPEA_H
#define CONCRETEPROTOTYPEA_H
#include "prototype.h"
class ConcretePrototypeA : public Prototype
{
public:
ConcretePrototypeA();
ConcretePrototypeA(int id);
virtual Prototype * Clone();
};
#endif // CONCRETEPROTOTYPEA_H
// concreteprototype.cpp
#include "concreteprototypea.h"
ConcretePrototypeA::ConcretePrototypeA()
{}
ConcretePrototypeA::ConcretePrototypeA(int id) : Prototype(id)
{}
Prototype * ConcretePrototypeA::Clone()
{
ConcretePrototypeA *p = new ConcretePrototypeA();
*p = *this;
return p;
}
客户端:
// main.cpp
#include <iostream>
#include "concreteprototypea.h"
using namespace std;
int main(int argc, char *argv[])
{
Prototype *p = new ConcretePrototypeA(101);
Prototype *p2 = p->Clone();
p->Show();
p2->Show();
return 0;
}