抽象工廠(Abstract Factory)模式看起來和前面看到的工廠方法很相似,只是它使用若干工廠方法(Factory Method)模式。每個工廠方法模式創建一個不同類型的對象。當創建一個工廠對象時,要決定將如何使用由那個工廠創建的所有對象。示例代碼如下(假設要創建一個通用的游戲環境,并且希望它能支持不同類型的游戲):
#include<iostream>
using namespace std;
class Obstacle
{
public:
virtual void action()=0;
};
class Player
{
public:
virtual void interactWith(Obstacle*)=0;
};
class Kitty: public Player
{
virtual void interactWith(Obstacle *ob)
{
cout<<"Kitty has encountered a";
ob->action();
}
};
class KungFuGuy: public Player
{
virtual void interactWith(Obstacle* ob)
{
cout<<"KungFuGuy now battles against a";
ob->action();
}
};
class Puzzle: 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;
};
//concreate 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)
:gef(factory),p(factory->makePlayer()),ob(factory->makeObstacle()){}
void play(){p->interactWith(ob);}
~GameEnvironment()
{
delete p;
delete ob;
delete gef;
}
};
int main()
{
GameEnvironment
g1(new KittiesAndPuzzles),
g2(new KillAndDismember);
g1.play();
g2.play();
}
在此環境中,Player對象與Obstacle 對象交互,但是Player和Obstacle類型依賴于具體的游戲。可以選擇特定的GameElementFactory來決定游戲的類型,然后GameEnvironment控制游戲的設置和進行。在本例中,游戲的設置和進行很簡單,但是那些動作在很大程度上決定了游戲的結果。