原型模式(Prototype)C++实现

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

 

实用性:1.当要实例化的类是在运行时刻指定时。

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

    3.当一个类的实例只能有几个不同状态组合中的一种时。

 

效果:   1.可以在运行时刻增加产品。

    2.改变值以指定新对象。

    3.改变结构以指定新对象。

    4.减少子类的构造。

    5.用类动态配置应用。

 

结构:

原型模式让我们不用重新初始化对象,而是动态地获得对象运行时的状态,并且在不确定对象类型的时候能

创建出对应新对象。

 

代码实例:

#ifndef _Prototype_
#define _Prototype_
#include <string>
#include <iostream>
using namespace std;

class AbsGoods{
public:
virtual AbsGoods* Clone() = 0;
string _mName;

protected:
AbsGoods(const AbsGoods& another){}
~AbsGoods(){}
AbsGoods(){}


int _Price;
};

class Mp3:public AbsGoods{
public:
Mp3(){_mName = "MP3"; _Price = 200;}
Mp3(const Mp3& another)
{
_mName = another._mName;
_Price = another._Price;
}

virtual AbsGoods* Clone()
{
return new Mp3(*this);
}
};

class Computer:public AbsGoods{
public:
Computer(const Computer& another)
{
_mName = another._mName;
_Price = another._Price;
}
Computer(){_mName = "COMPUTER"; _Price = 4000;}

virtual AbsGoods* Clone()
{
return new Computer(*this);
}
};

class Person{
public:
Person(){_CountGoods = 0;}
bool addGoods(AbsGoods* aGoods)
{
if(NULL == aGoods) return false;
if(_CountGoods >= 10)
return false;
_myGoods[_CountGoods] = aGoods;
_CountGoods++;
return true;
}
void out()
{
for(int i=0; i<_CountGoods; i++)
{
cout<<_myGoods[i]->_mName<<" ";
}
}
AbsGoods* getGoods(int Num)
{
return _myGoods[Num-1];
}

private:
AbsGoods* _myGoods[10];
int _CountGoods;
};

class Mical : public Person{
public:
static Mical* getMical()
{
if(NULL == _thisMical)
{
_thisMical = new Mical;
}
return _thisMical;
}

private:
Mical(){}
Mical(const Mical& another){}
void operator = (const Mical& another);

static Mical* _thisMical;
};

class Merry : public Person{
public:
static Merry* getMerry()
{
if(NULL == _thisMerry)
{
_thisMerry = new Merry;
}
return _thisMerry;
}

private:
Merry(){}
Merry(const Merry& another){}
void operator = (const Merry& another);

static Merry* _thisMerry;
};

#endif

 

现Mical有一台电脑和一架Mp3

mical->addGoods(new Computer);
mical->addGoods(new Mp3);

 

然后Merry觉得Mical有的我也要有

for(int i=0; i<mical->getGoodsNum(); i++)
{
merry->addGoods(mical->getGoods(i+1)->Clone());
}

这里实现了不确定对象类型的时候能创建出对应新对象

 

mian函数代码如下:

#include <iostream>

using namespace std;

#include "Prototype.h"

Mical* Mical::_thisMical = NULL;
Merry* Merry::_thisMerry = NULL;

int main()
{
Mical* mical = Mical::getMical();
Merry* merry = Merry::getMerry();

mical->addGoods(new Computer);
mical->addGoods(new Mp3);

for(int i=0; i<mical->getGoodsNum(); i++)
{
merry->addGoods(mical->getGoods(i+1)->Clone());
}

cout<<"Mical's Goods : ";
mical->out();
cout<<endl;
cout<<"Merry's Goods : ";
merry->out();

return 0;
}

posted @ 2014-12-18 13:14  吴筱军  阅读(2231)  评论(0编辑  收藏  举报