全部博文(156)
分类: C/C++
2011-03-21 14:00:30
现在可以看到,想新来做一个菜系,只需新聘请一个厨师就可以了,多么完美,但是如果你想新增加一个菜就变得非常困难了。
#include
using namespace std;
//meat base
class baseMeat
{
public:
virtual void getMeat(){};
};
//braising meat
class braisingMeat:public baseMeat
{
public:
void getMeat()
{
cout <<"this is braising meat\n";
};
};
//steamed meat
class steamedMeat:public baseMeat
{
public:
void getMeat()
{
cout <<"this is steamed meat\n";
};
};
//fish base
class baseFish
{
public:
virtual void getFish(){};
};
//braising fish
class braisingFish:public baseFish
{
public:
void getFish()
{
cout <<"this braising fish\n";
};
};
class steamedFish:public baseFish
{
public:
void getFish()
{
cout <<"this is steamed fish\n";
};
};
//factory base
class factoryBase
{
public:
virtual baseMeat *createMeat(){};
virtual baseFish *createFish(){};
};
class braisingFactory:public factoryBase
{
public:
baseMeat *createMeat()
{
return new braisingMeat;
};
baseFish *createFish()
{
return new braisingFish;
};
};
class steamedFactory:public factoryBase
{
public:
baseMeat *createMeat()
{
return new steamedMeat;
};
baseFish *createFish()
{
return new steamedFish;
};
};
int main()
{
factoryBase *factory = new braisingFactory;
baseMeat *meat = factory->createMeat();
baseFish *fish = factory->createFish();
meat->getMeat();
fish->getFish();
delete factory;
delete meat;
delete fish;
factory = new steamedFactory;
meat = factory->createMeat();
fish = factory->createFish();
meat->getMeat();
fish->getFish();
return 0;
}
适用性:
一个系统要独立于它的产品的创建、组合和表示时
一个系统要由多个 产品系列中的一个来配置时
当你要强调一个系列相关的产品对象的设计以便进行联合使用时
当你提供一个产品类库,而只想显示它们的接口而不是实现时。