# Builder pattern ## Problem To build a simple house, you need to construct four walls and a floor, install a door, fit a pair of windows, and build a roof. But what if you want a bigger, brighter house, with a backyard and other goodies (like a heating system, plumbing, and electrical wiring)? ### extend the base House class ![](https://i.imgur.com/pU7VR3g.png) you’ll end up with a considerable number of subclasses. ## another approach ![](https://i.imgur.com/1t2I7YY.png) In most cases most of the parameters will be unused, making the constructor calls pretty ugly. ## Solution: Builder pattern ![](https://i.imgur.com/5A5aXHv.png) ``` builder.buildWalls() builder.buildDoors() builder.buildWindows() builder.buildRoof() # Add garage builder.buildGarage() house = builder.getResult() ``` ## when you need to build various representations of the product ![](https://i.imgur.com/Ekefstc.png) ## Director ![](https://i.imgur.com/qHGxXgb.png) Director: defines the order in which to execute the building steps Builder: provides the implementation for those steps. (Having a director class in your program isn’t strictly necessary) ![](https://i.imgur.com/OIntOcF.png) ## Pseudocode ![](https://i.imgur.com/zMLuMq5.png) ## Applicability 1. Use the Builder pattern to get rid of a “telescoping constructor”. ![](https://i.imgur.com/ZSwlY1W.png) 2. Use the Builder pattern when you want your code to be able to create different representations of some product (for example, stone and wooden houses). ![](https://i.imgur.com/EOZH3cU.png) 3. Use the Builder to construct Composite trees or other complex objects. ![](https://i.imgur.com/l4fgUBa.png) ## Builder vs Abstract Factory ![](https://i.imgur.com/qptU7Jv.png) ![](https://i.imgur.com/dX7sC9c.png)