根据网上资料整理一个工厂方法模式的示例分析如下:
水果包括苹果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就可以了,不需要修改其他部分内容)

posted on 2007-04-18 08:26  许维光  阅读(189)  评论(0)    收藏  举报