您的位置:首页 > 产品设计 > UI/UE

笔记:Gof设计模式--Builder

2012-05-29 21:56 218 查看
1、意图

Separate the construction of a complex object from its representation the same construction process can create different representations.

2、适应性
Use the builder pattern when
• the algorithm for creating a complex object should be independent of the parts that make up the object and
how they're assembled.
• the construction process must allow different representations for the object that's constructed.
3、结构



[align=left] [/align]

4、示例代码

The MazeBuilder class defines the following interface for building mazes:

class MazeBuilder {
public:
virtual void BuildMaze() { }
virtual void BuildRoom(int room) { }
virtual void BuildDoor(int roomFrom, int roomTo) { }

virtual Maze* GetMaze() { return 0; }
protected:
MazeBuilder();
};


The subclass StandardMazeBuilder is an implementation that builds simple mazes. It keeps track of the maze it's building in the variable _currentMaze.

class StandardMazeBuilder : public MazeBuilder {
public:
StandardMazeBuilder();

virtual void BuildMaze();
virtual void BuildRoom(int);
virtual void BuildDoor(int, int);

virtual Maze* GetMaze();
private:
Direction CommonWall(Room*, Room*);
Maze* _currentMaze;
};


// The StandardMazeBuilder constructor simply initializes _currentMaze.
StandardMazeBuilder::StandardMazeBuilder () {
_currentMaze = 0;
}

void StandardMazeBuilder::BuildMaze () {
_currentMaze = new Maze;
}

Maze* StandardMazeBuilder::GetMaze () {
return _currentMaze;
}


// The BuildRoom operation creates a room and builds the walls around it:
void StandardMazeBuilder::BuildRoom (int n) {
if (!_currentMaze->RoomNo(n)) {
Room* room = new Room(n);
_currentMaze->AddRoom(room);

room->SetSide(North, new Wall);
room->SetSide(South, new Wall);
room->SetSide(East, new Wall);
room->SetSide(West, new Wall);
}
}

void StandardMazeBuilder::BuildDoor (int n1, int n2) {
Room* r1 = _currentMaze->RoomNo(n1);
Room* r2 = _currentMaze->RoomNo(n2);
Door* d = new Door(r1, r2);

r1->SetSide(CommonWall(r1,r2), d);
r2->SetSide(CommonWall(r2,r1), d);
}


Maze* MazeGame::CreateMaze (MazeBuilder& builder) {
builder.BuildMaze();

builder.BuildRoom(1);
builder.BuildRoom(2);
builder.BuildDoor(1, 2);

return builder.GetMaze();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: