全部博文(512)
分类: C/C++
2006-08-29 09:08:48
概念:
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
Builder模式的一个大的特点是允许Director(或者说用户)按照自己需要的次序去创建一组对象,灵活性大。
Abstract Factory (3 . 1)与B u i l d e r相似,因为它也可以创建复杂对象。主要的区别是
B u i l d e r模式着重于一步步构造一个复杂对象。而Abstract Factory着重于多个系列的产品对象
(简单的或是复杂的)。B u i l d e r在最后的一步返回产品,而对于Abstract Factory来说,产品是立即返回的。C o m p o s i t e(4 . 3)通常是用B u i l d e r生成的。
举例:
//创建者基类 这个类提供创建复杂对象的接口 接口的实现在子类中实现
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();
};
//客户,MazeGame是使用这个对象的客户
Maze* MazeGame::CreateMaze (MazeBuilder& builder) {
builder.BuildMaze();
builder.BuildRoom(1);
builder.BuildRoom(2);
builder.BuildDoor(1, 2);
return builder.GetMaze();
}
//创建者子类 对基类中方法进行实现 以便控制创建结果
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;
};
StandardMazeBuilder::StandardMazeBuilder () {
_currentMaze = 0;}
void StandardMazeBuilder::BuildMaze () {
_currentMaze = new Maze;
}
Maze* StandardMazeBuilder::GetMaze () {
return _currentMaze;
}
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* maze;
MazeGame game;
StandardMazeBuilder builder;
//在这里进行创建 产生一个maze
game.CreateMaze(builder);
maze = builder.GetMaze();
//第二个子类 提供第二种创建方法
class CountingMazeBuilder : public MazeBuilder {
public:
CountingMazeBuilder();
virtual void BuildMaze();
virtual void BuildRoom(int);
virtual void BuildDoor(int, int);
virtual void AddWall(int, Direction);
void GetCounts(int&, int&) const;
private:
int _doors;
int _rooms;
};
CountingMazeBuilder::CountingMazeBuilder () {
_rooms = _doors = 0;
}
void CountingMazeBuilder::BuildRoom (int) {
_rooms++;
}
void CountingMazeBuilder::BuildDoor (int, int) {
_doors++;
}
void CountingMazeBuilder::GetCounts (
int& rooms, int& doors
) const {
rooms = _rooms;
doors = _doors;
}
//使用例子
int rooms, doors;
MazeGame game;
CountingMazeBuilder builder;
//创建并返回对象 和上面相比 不同点在于传进去的子类不同了 这里是传CountingMazeBuilder 类的对象 所以产生结果也不一样
game.CreateMaze(builder);
builder.GetCounts(rooms, doors);