Middle
What is a builder in the context of software design?
sobes.tech AI
Answer from AI
This is a creational design pattern that separates the construction of a complex object from its representation, allowing the same construction process to create different representations of the object.
How it works:
- Product: The complex object to be built.
- Builder: An abstract interface for creating parts of the product.
- Concrete Builder: Implements the Builder interface to create specific parts and assemble them into a complete product.
- Director (optional): Defines the order of construction steps and uses the Builder to create the product.
Advantages:
- Allows step-by-step construction of complex objects.
- Separates the construction logic from the object itself.
- Enables creating different representations of the object using the same process.
- Facilitates extension by adding new Concrete Builders.
Disadvantages:
- Increases the number of classes due to the need for separate Concrete Builders.
- Can complicate code for simple objects.
Example in Java:
Let's consider creating a complex object "House":
// Product
class House {
private String walls;
private String roof;
private String windows;
private String doors;
public void setWalls(String walls) { this.walls = walls; }
public void setRoof(String roof) { this.roof = roof; }
public void setWindows(String windows) { this.windows = windows; }
public void setDoors(String doors) { this.doors = doors; }
@Override
public String toString() {
return "House{" +
"walls='" + walls + '\'' +
", roof='" + roof + '\'' +
", windows='" + windows + '\'' +
", doors='" + doors + '\'' +
'}';
}
}
// Builder
interface HouseBuilder {
void buildWalls();
void buildRoof();
void buildWindows();
void buildDoors();
House getResult();
}
// Concrete Builder
class StoneHouseBuilder implements HouseBuilder {
private House house;
public StoneHouseBuilder() {
this.house = new House();
}
@Override
public void buildWalls() {
house.setWalls("Stone Walls");
}
@Override
public void buildRoof() {
house.setRoof("Tile Roof");
}
@Override
public void buildWindows() {
house.setWindows("Wooden Windows");
}
@Override
public void buildDoors() {
house.setDoors("Solid Wooden Doors");
}
@Override
public House getResult() {
return house;
}
}
// Director (optional)
class Director {
public void constructStoneHouse(HouseBuilder builder) {
builder.buildWalls();
builder.buildRoof();
builder.buildWindows();
builder.buildDoors();
}
}
// Usage
public class BuilderExample {
public static void main(String[] args) {
Director director = new Director();
HouseBuilder stoneHouseBuilder = new StoneHouseBuilder();
director.constructStoneHouse(stoneHouseBuilder);
House stoneHouse = stoneHouseBuilder.getResult();
System.out.println(stoneHouse); // Output: House{walls='Stone Walls', roof='Tile Roof', windows='Wooden Windows', doors='Solid Wooden Doors'}
}
}