设计模式之工厂模式

根据网上资料整理一个工厂方法模式的示例分析如下:
水果包括苹果Apple,葡萄Grape。 ----这是产品角色类
工厂为水果种植者(FruitGardener)所种植,水果种植者包括苹果种植者(AppleGardener)和葡萄种植者(GrapeGardener)。
class Fruit
{
public:
virtual void grow()=0;
virtual void plant()=0;
};

class Apple :public Fruit
{
public:
void grow() { std::cout<<"Apple be produced!"<<endl; }
void plant() { std::cout<<"Apple be planted!"<<endl; }
};

class Grape : public Fruit
{
public:
void grow() { std::cout<<"Grape be produced!"<<endl; }
void plant() { std::cout<<"Grape be planted!"<<endl; }

};

class FruitGardener
{
public:
virtual Fruit * Produce()=0;
};

class AppleGardener : public FruitGardener
{
public :
Apple * Produce()
{ return new Apple(); }
};

class GrapeGardener : public FruitGardener
{
public :
Grape * Produce()
{ return new Grape(); }
};


//使用如上代码模块
FruitGardener * pAG = new AppleGardener();
FruitGardener * pGG = new GrapeGardener();

Fruit * pA = pAG.Produce();
Fruit * pG = pGG.Produce();
这就是工厂方法的模式,在需要增加新的水果时候,只需要添加水果类和水果工厂(即其对应的Gardener就可以了,不需要修改其他部分内容) 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值