设计模式之工厂模式
2007-04-04 17:31
120 查看
根据网上资料整理一个工厂方法模式的示例分析如下:
水果包括苹果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就可以了,不需要修改其他部分内容)
水果包括苹果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就可以了,不需要修改其他部分内容)
相关文章推荐
- 设计模式之一:Java中的简单工厂模式
- 设计模式之工厂模式
- java的工厂设计模式实例
- 设计模式之简单工厂模式(静态工厂方法)
- [原创]设计模式----简单工厂模式
- 设计模式:抽象工厂方法模式
- java设计模式--创建模式--工厂方法
- Java设计模式之工厂模式
- 设计模式学习之简单工厂、工厂方法、抽象工厂
- 设计模式-旧话重提之类工厂的使用
- Java设计模式之工厂方法模式
- [设计模式]-简单工厂模式
- C#用工厂模式、反射机制和缓存机制来设计数据访问层的接口
- 【设计模式】三大工厂家族
- 写给新手的设计模式教程——[静态]工厂模式
- 设计模式之简单工厂模式
- java设计模式之工厂模式
- 设计模式学习笔记(二)--简单工厂模式
- 设计模式之工厂系列
- C#设计模式--工厂方法