Abstract Factory抽象工廠模式實際上只是使用多個Factory Method。每個Factory Method創(chuàng)建一個不同類型的對象。下面的例子代碼假設(shè)要創(chuàng)建一個通用的游戲環(huán)境,并支持不同類型的游戲。
#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 *///