Benjamin

静以修身,俭以养德,非澹薄无以明志,非宁静无以致远。
随笔 - 397, 文章 - 0, 评论 - 196, 引用 - 0
数据加载中……

设计模式之factory工厂模式(三):Abstract Factory抽象工厂模式

Abstract Factory抽象工厂模式实际上只是使用多个Factory Method。每个Factory Method创建一个不同类型的对象。下面的例子代码假设要创建一个通用的游戏环境,并支持不同类型的游戏。
#include <iostream>
using namspace std;

class Obstacle{
 public:
   virtural void action()=0;
};//抽象基类

class Player{
public:
   virtural void interactWith(Obstacle*)=0;
};//抽象基类

class Kitty:public Player{
   virtual void interactWith(Obstacle*){
   cout<<"KungFuGuy now battles against a";
   ob->action();
};

class Puzzile:public Obstacle{
public:
   void action(){
      cout << "Puzzle" << endl;}
};

class NastyWeapon:public Obstacle{
public:
   void action(){
      cout << "NastyWeapon" << endl;}
}; 

//The abstract factory
class GameElementFactory{
public:
   virtual Player* makePlayer()=0;
   virtual Obstacle* makeObstacle()=0;
};

//Concreae factories
class KittiesAndPuzzles:public GameElementFactory{
public:
   virtual Player* makePlayer() {return new Kitty;}
   virtual Obstacle* makeObstacle() {return new Puzzle;}
};

class KillAndDismember:public GameElementFactory{
public:
   virtual Player* makePlayer() {return new KungFuGuy;}
   virtual Obstacle* makeObstacle() {return new NastyWeapon;}
};

class GameEnvironment{
   GameElementFactory* gef;
   Player* p;
   Obstacle* ob;
public:
   GameEnvironment(GameElementFactory* factory):get(factory),p(factory->makePlayer()),ob(factory->makeObstacle()){}
void play() {p->interacWith(ob);}
~GameEnvrionment(){
   delete p;
   delete ob;
   delete gef;
   }
};

int main(){
   GameEnvironment g1(new KittiesAndPuzzles),g2(new KillAndDismember);
   g1.play();
   g2.play();
}

/* Output:
Kitty has encountered a Puzzle
KungFuGuy now battles against a NastyWeapon *///

posted on 2009-04-14 22:04 Benjamin 阅读(403) 评论(1)  编辑 收藏 引用 所属分类: C/C++

评论

# re: 设计模式之factory工厂模式(三):Abstract Factory抽象工厂模式  回复  更多评论   

//这两个class要修正一下:
class Kitty:public Player{
virtual void interactWith(Obstacle* ob){
cout<< "Kitty ha encountered a ";
ob->action();
}
};
class KungFuGuy:public Player{
virtual void interactWith(Obstacle* ob){
cout <<"KungFuGuy now battles against a ";
ob->action();
}
};
2009-09-04 21:05 | 李熙建

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理