Builder Pattern
Builder Pattern
The Builder Pattern is a creational design pattern that provides a way to construct a complex
object step by step. It separates the construction of a complex object from its representation,
allowing the same construction process to create different representations.
This pattern is particularly useful when an object has a large number of parameters, and it
becomes cumbersome to pass them all to the constructor.
The Builder Pattern typically involves the following components:
1. Director:
The Director is responsible for orchestrating the construction of the product. It directs the builder
on how to build the various parts and when to assemble them to create the final product.
2. Builder:
The Builder is an interface or an abstract class that declares the construction steps for building
the product. It provides methods for constructing each part of the complex object.
3. Concrete Builder:
Concrete Builder classes implement the Builder interface. They provide specific implementations
for the construction steps, building the parts of the complex object.
4. Product:
The Product is the complex object being constructed. It may have a complex internal structure
made up of several parts.
Here's a simplified example to illustrate the Builder Pattern. Let's say we want to build a Meal
object that consists of a Burger, Drink, and Dessert. The Meal is our complex object.
// Product: Meal
public class Meal {
private String burger;
private String drink;
private String dessert;
@Override
public String toString() {
return "Meal{" +
"burger='" + burger + '\'' +
", drink='" + drink + '\'' +
", dessert='" + dessert + '\'' +
'}';
}
}
// Builder: MealBuilder
public interface MealBuilder {
MealBuilder addBurger();
MealBuilder addDrink();
MealBuilder addDessert();
Meal build();
}
public VegMealBuilder() {
this.meal = new Meal();
}
@Override
public MealBuilder addBurger() {
meal.setBurger("Veg Burger");
return this;
}
@Override
public MealBuilder addDrink() {
meal.setDrink("Coke");
return this;
}
@Override
public MealBuilder addDessert() {
meal.setDessert("Ice Cream");
return this;
}
@Override
public Meal build() {
return meal;
}
}
@Override
public MealBuilder addBurger() {
meal.setBurger("Chicken Burger");
return this;
}
@Override
public MealBuilder addDrink() {
meal.setDrink("Pepsi");
return this;
}
@Override
public MealBuilder addDessert() {
meal.setDessert("Chocolate Cake");
return this;
}
@Override
public Meal build() {
return meal;
}
}
// Director: Waiter
public class Waiter {
private MealBuilder mealBuilder;
// Application
public class Application {
public static void main(String[] args) {
MealBuilder vegMealBuilder = new VegMealBuilder();
MealBuilder nonVegMealBuilder = new NonVegMealBuilder();