关闭

设计模式--工厂方法

标签: 设计模式工厂方法 示例代码
450人阅读 评论(0) 收藏 举报
分类:

//代码示例

#include <iostream>
using namespace std;

enum
{
	North, 
	South,
	East,
	West,
};

enum GameType
{
	FIRST,
	SECOND,
	THREE,
	END,
};

class Maze;//迷宫
class Room;//房间
class Wall;//墙
class Door;//门

//基类
class MazeGame
{
public:
	MazeGame();
public:
	Maze* CreateMaze();
public:
	virtual Maze* MakeMaze() const
	{
		return new Maze;
	}
	virtual Room* MakeRoom(int n) const
	{
		return new Room(n);
	}
	virtual Maze* MakeWall() const
	{
		return new Wall;
	}
	virtual Maze* MakeDoor(Room* r1, Room* r2) const
	{
		return new Door(r1, r2);
	}
private:
};

Maze* MazeGame::CreateMaze()
{
	Maze* aMaze = MakeMaze();

	Room* r1 = MakeRoom(1);
	Room* r2 = MakeRoom(2);
	Door* theDoor = MakeDoor(r1, r2);

	aMaze->AddRoom(r1);
	aMaze->AddRoom(r2);

	r1->SetSide(North, MakeWall());
	r1->SetSide(East, theDoor);
	r1->SetSide(South, MakeWall());
	r1->SetSide(West, MakeWall());

	r2->SetSide(North, MakeWall());
	r2->SetSide(East,  MakeWall());
	r2->SetSide(South, MakeWall());
	r2->SetSide(West,  theDoor);
}

//子类
class BombeWall;
class RoomWithABomb;

class BombeMazeGame : public MazeGame
{
public:
	BombeMazeGame();
public:
	virtual Wall* MakeWall() const
	{
		return new BombeWall;
	}
	virtual Room* MakeRoom(int n) const
	{
		return new RoomWithABomb(n);
	}
private:
};

//子类
class EnchantedRoom;
class DoorNeedingSpell;

class EnchantedMazeGame : public MazeGame
{
public:
	EnchantedMazeGame();
public:
	virtual Room* MakeRoom(int n) const
	{
		return new Room(n);
	}
	virtual Maze* MakeDoor(Room* r1, Room* r2) const
	{
		return new DoorNeedingSpell(r1, r2);
	}
private:
};


//模式应用
class Consumer
{
public:
	Consumer();
public:
	MazeGame* CreateMaze(GameType type);//工厂方法(函数)
private:
};
//工厂方法(函数)实现

MazeGame* Consumer::CreateMaze(GameType type)
{
	switch (type)
	{
	case FIRST:
		{
			return MazeGame;
		}
		break;
	case SECOND:
		{
			return BombeMazeGame;
		}
		break;
	case THREE:
		{
			return EnchantedMazeGame;
		}
		break;
	}
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:25346次
    • 积分:729
    • 等级:
    • 排名:千里之外
    • 原创:48篇
    • 转载:16篇
    • 译文:0篇
    • 评论:0条
    文章分类