设计模式-Prototype(通过复制构造函数实现自我复制)-(创建型模式)
以下代码来源: 设计模式精解-GoF 23种设计模式解析附C++实现源码
//Prototype.h
#pragma once class Prototype { public: virtual ~Prototype(); virtual Prototype* clone() const = 0; protected: Prototype(); private: }; class concreatePrototype :public Prototype { public: concreatePrototype(); ~concreatePrototype(); concreatePrototype(const concreatePrototype& cp); Prototype* clone()const; private: protected: };
//Prototype.cpp
#include"Prototype.h" #include<iostream> #include<string> Prototype::Prototype(){} Prototype::~Prototype(){} Prototype* Prototype::clone()const { return 0; } concreatePrototype::concreatePrototype(){} concreatePrototype::~concreatePrototype(){} concreatePrototype::concreatePrototype(const concreatePrototype& cp) { std::cout << "ConcreatePrototype Copy." << std::endl; } Prototype* concreatePrototype::clone()const { return (new concreatePrototype(*this)); }
//main.cpp
#include"Prototype.h" int main(int args, char* argv) { Prototype* p = new concreatePrototype(); Prototype* p_clone = p->clone(); return 0; }