中国 - 喜马拉雅

       Let life be beautiful like summer flowers . . .

抽像工厂(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;
};

// Concrete 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();
}
/* Output:
Kitty has encountered a Puzzle
KungFuGuy now battles against a NastyWeapon */

在此正境中,Player对象与Obstacle对象交互,但是Player和Obstacle类型依赖于具体的游戏。可以选择特定的GameElementFactory来决定游戏的类型,然后GameEnvironment控制游戏的设置和进行。

选自《C++编程思想》。

posted on 2012-10-02 10:20  chinaxmly  阅读(274)  评论(2编辑  收藏  举报