skip to content
Mohammad Rebati

Understanding the Builder Design Pattern

/ 2 min read

Introduction to the Builder Design Pattern

The Builder Design Pattern is a creational pattern used to construct a complex object step by step. It separates the construction of a complex object from its representation so that the same construction process can create different representations. This pattern is particularly useful when an object requires many steps to be created or involves many components.

Key Concepts

  • Builder: Provides the interface for creating parts of a Product object.
  • Concrete Builder: Implements the Builder interface and provides specific implementations for the building steps. It also provides a method to retrieve the final product.
  • Director: Responsible for managing the construction process using a Builder object.
  • Product: Represents the complex object being constructed.

Benefits

  • Flexibility: Allows changing the internal representation of products by changing the concrete builder.
  • Control over Construction Process: Construction is shielded from the details of the product’s components and how they’re assembled.
  • Reusability: The same construction process can create different representations.

Example in Code

Here’s how you might implement the Builder Pattern in C# for creating different types of pizzas:

// Product
public class Pizza
{
public string Dough { get; set; }
public string Sauce { get; set; }
public string Topping { get; set; }
public void ShowPizza()
{
Console.WriteLine($"Pizza with {Dough} dough, {Sauce} sauce and {Topping} topping.");
}
}
// Builder interface
public interface IPizzaBuilder
{
void BuildDough();
void BuildSauce();
void BuildTopping();
Pizza GetPizza();
}
// Concrete Builder
public class HawaiianPizzaBuilder : IPizzaBuilder
{
private Pizza _pizza = new Pizza();
public void BuildDough()
{
_pizza.Dough = "cross";
}
public void BuildSauce()
{
_pizza.Sauce = "mild";
}
public void BuildTopping()
{
_pizza.Topping = "ham+pineapple";
}
public Pizza GetPizza()
{
return _pizza;
}
}
public class SpicyPizzaBuilder : IPizzaBuilder
{
private Pizza _pizza = new Pizza();
public void BuildDough()
{
_pizza.Dough = "pan baked";
}
public void BuildSauce()
{
_pizza.Sauce = "hot";
}
public void BuildTopping()
{
_pizza.Topping = "pepperoni+salami";
}
public Pizza GetPizza()
{
return _pizza;
}
}
// Director
public class Cook
{
public void MakePizza(IPizzaBuilder pizzaBuilder)
{
pizzaBuilder.BuildDough();
pizzaBuilder.BuildSauce();
pizzaBuilder.BuildTopping();
}
}
// Example usage
class Program
{
static void Main(string[] args)
{
Cook cook = new Cook();
IPizzaBuilder hawaiianPizzaBuilder = new HawaiianPizzaBuilder();
cook.MakePizza(hawaiianPizzaBuilder);
Pizza pizza = hawaiianPizzaBuilder.GetPizza();
pizza.ShowPizza();
IPizzaBuilder spicyPizzaBuilder = new SpicyPizzaBuilder();
cook.MakePizza(spicyPizzaBuilder);
pizza = spicyPizzaBuilder.GetPizza();
pizza.ShowPizza();
}
}