Junior
What is the essence of the Builder design pattern?
sobes.tech AI
Answer from AI
Builder is a creational pattern that allows step-by-step creation of complex objects, separating the construction process from its representation. It provides an interface for constructing an object step by step, and various concrete builders implement this interface to create different representations of the same object.
The essence of Builder is as follows:
- Step-by-step construction: Instead of a single large constructor or factory method, Builder breaks down the process of creating an object into separate steps.
- Separation of process and representation: The client interacts with the Builder to create an object but does not know the details of its internal structure or the order of assembly.
- Flexibility: It allows creating different variants of an object using the same construction process, simply by changing the Concrete Builder.
- Avoiding Telescoping Constructor: It solves the problem of having multiple constructors with different numbers of parameters, making the code more readable and maintainable.
Example: Creating a Pizza object with various ingredients.
// Builder interface
interface PizzaBuilder {
void buildDough();
void buildSauce();
void buildTopping();
Pizza getPizza();
}
// Concrete Builder
class MargheritaPizzaBuilder implements PizzaBuilder {
private Pizza pizza = new Pizza();
@Override
public void buildDough() {
pizza.setDough("thin crust");
}
@Override
public void buildSauce() {
pizza.setSauce("tomato");
}
@Override
public void buildTopping() {
pizza.setTopping("mozzarella");
}
@Override
public Pizza getPizza() {
return pizza;
}
}
// The object being built
class Pizza {
private String dough;
private String sauce;
private String topping;
public void setDough(String dough) {
this.dough = dough;
}
public void setSauce(String sauce) {
this.sauce = sauce;
}
public void setTopping(String topping) {
this.topping = topping;
}
@Override
public String toString() {
return "Pizza{" +
"dough='" + dough + '\'' +
", sauce='" + sauce + '\'' +
", topping='" + topping + '\'' +
'}';
}
}
// Director (optional), manages the construction process
class Director {
public void constructMargherita(PizzaBuilder builder) {
builder.buildDough();
builder.buildSauce();
builder.buildTopping();
}
}
// Client code
public class Main {
public static void main(String[] args) {
Director director = new Director();
PizzaBuilder builder = new MargheritaPizzaBuilder();
director.constructMargherita(builder);
Pizza pizza = builder.getPizza();
System.out.println(pizza); // Output: Pizza{dough='thin crust', sauce='tomato', topping='mozzarella'}
}
}