Builder

Separates the construction of a complex object from its representation so that the same construction process can create different representations. Use it when the algorithm for creating a complex object should be independent of its constituent parts and their assembly, and when the construction process must support different representations of the constructed object.

Examples:

  • Building a House object could require walls, doors, windows, a roof, a heating system, plumbing, and a swimming pool in any combination. Instead of a constructor with dozens of parameters or an explosion of subclasses, the Builder pattern extracts construction steps (buildWalls, addDoor, addPool) into a builder object; a Director can orchestrate common configurations while client code calls only the steps it actually needs.
// Director drives construction via abstract builder interface
class MazeBuilder {
public:
  virtual void BuildMaze()           {}
  virtual void BuildRoom(int n)      {}
  virtual void BuildDoor(int r1, int r2) {}
  virtual Maze* GetMaze()            { return nullptr; }
};
// Director calls builder steps; concrete builders vary the result
Maze* CreateMaze(MazeBuilder& builder) {
  builder.BuildMaze();
  builder.BuildRoom(1); builder.BuildRoom(2);
  builder.BuildDoor(1, 2);
  return builder.GetMaze();
}