What is the Builder pattern?
Builder is a creational design pattern that splits the process of building a complex object into separate steps, letting you assemble it step by step and in different variations without changing the overall algorithm.
1. Why it is needed
When an object has many parameters (required and optional), a plain constructor becomes inconvenient and hard to read. Builder solves this by letting you build the object gradually, specifying only the parameters you need, while the assembly process itself can be changed independently of the object's structure.
2. The core idea
Instead of a bulky constructor:
new House("brick", 2, true, false, "tile", "garden");step-by-step assembly is used:
House house = new HouseBuilder()
.setWalls("brick")
.setFloors(2)
.setGarage(true)
.build();3. Structure
- Builder - an interface that describes the steps for building the product.
- ConcreteBuilder - implements the steps and holds the object being assembled.
- Director (optional) - controls the order of assembly (defines the recipe).
- Product - the final object that needs to be built.
4. Example (Java)
class House {
private String walls;
private String roof;
private boolean garage;
// private constructor
private House(String walls, String roof, boolean garage) {
this.walls = walls;
this.roof = roof;
this.garage = garage;
}
public static class Builder {
private String walls;
private String roof;
private boolean garage;
public Builder setWalls(String walls) { this.walls = walls; return this; }
public Builder setRoof(String roof) { this.roof = roof; return this; }
public Builder setGarage(boolean garage) { this.garage = garage; return this; }
public House build() {
return new House(walls, roof, garage);
}
}
}Usage:
House h = new House.Builder()
.setWalls("brick")
.setRoof("tile")
.setGarage(true)
.build();5. Advantages
- Simplifies creating complex objects.
- Lets you use different assembly variants for the same product.
- Makes the code readable and flexible.
- Removes the need for long constructors.
6. Disadvantages
- Increases the number of classes.
- More complex than a plain constructor when the object is simple.
Summary: Builder separates construction from the representation of an object, letting you build complex structures step by step with different combinations of parameters without overloading constructors or confusing the code.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.