抽像工厂模式

抽像工厂(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++编程思想》。

原文链接: https://www.cnblogs.com/chinaxmly/archive/2012/10/02/2710172.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    抽像工厂模式

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/64657

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 上午11:27
下一篇 2023年2月9日 上午11:29

相关推荐