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

设计模式之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 *///

你可能感兴趣的:(设计模式之factory工厂模式(三):Abstract Factory抽象工厂模式)