笔记:Gof设计模式--Builder

来源:互联网 发布:上海至寻网络骗局 编辑:程序博客网 时间:2024/05/29 02:10

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、结构

 

 

 

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();     } 


 

原创粉丝点击