设计模式-原型模式

来源:互联网 发布:哪个看书软件好 编辑:程序博客网 时间:2024/06/10 05:40

适用情境:一个对象复制自身.

这里写图片描述

// prototype.h#ifndef PROTOTYPE_H#define PROTOTYPE_Hclass 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;}
0 0