设计模式C++原型模式(Prototype)

意图:

   用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

适用性:

    当一个系统应该独立于他的产品创建、构成和表示时,需要使用原型模式

    当要实例化的类是在运行时刻指定时,如通过动态装载

    为了避免创建一个与产品类层次平行的工厂类层次时

    当一个类的实例只能有几个不同状态组合中的一种时,建立相应数目的原型并克隆他们可能比每次用合适的状态手工实例化该类更方便一些。

1、

#ifndef _PATTERNPROTOTYPE_H_
#define _PATTERNPROTOTYPE_H_

#include <iostream>
using namespace std;

class Prototype
{
protected :
    int age;
public :
    Prototype(){}
    virtual ~Prototype(){}
    //纯虚函数,需要供继承者自行实现
    virtual Prototype * clone()=0;

    void setAge(int age)
    {
        this->age=age;
    }
    int getAge()
    {
        return age;
    }
};

class PrototypeOne:public Prototype
{
public :
    PrototypeOne()
    {
        cout<<"Prototype create"<<endl;
    }
    PrototypeOne(PrototypeOne & one)
    {
        cout<<"copy the PrototypeOne"<<endl;
    }
    virtual ~ PrototypeOne()
    {
        cout<<"destruction of PrototypeOne"<<endl;
    }
    virtual Prototype * clone()
    {
        return new PrototypeOne(*this); 
    }
};

#endif

2、

#include <iostream>  

#include <string>
#include "PatternPrototype.h"

using namespace std;  


int main()  
{  
    Prototype *prototype=new PrototypeOne();
    Prototype *copytype1 = prototype->clone(); 
    cout<<prototype->getAge()<<endl;
    cout<<copytype1->getAge()<<endl;
    prototype->setAge(200);
    copytype1->setAge(100);
    cout<<prototype->getAge()<<endl;
    cout<<copytype1->getAge()<<endl;

    delete prototype;  
    delete copytype1; 

    system("pause");  
    return 0;  
}  
发布了47 篇原创文章 · 获赞 6 · 访问量 10万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章