Builder Design Pattern is used to build complex objects using simple objects and using a step-by-step approach. The process of constructing a complex object is generalized so that the same construction process can be used to create different representations of the same complex object
The Builder pattern is a creational design pattern that lets you construct complex objects step by step. It allows you to produce different types and representations of an object using the same construction code.
This implementation demonstrates a beverage preparation system where different types of beverages (Tea and Coffee) are built using the same construction process:
- Beverage (Product): The complex object being built with properties like Water, Milk, Sugar, PowderQuantity, and BeverageName
- BeverageBuilder (Abstract Builder): Defines the construction interface
- BeverageDirector (Director): Controls the construction process using a builder
- Concrete Builders: TeaBuilder and CoffeeBuilder that implement specific construction steps
Beverage- Product class with beverage properties and ShowBeverage() methodBeverageBuilder- Abstract builder defining construction steps (SetWater, SetMilk, SetSugar, SetPowderQuantity, SetBeverageType)BeverageDirector- Director that orchestrates the building process through MakeBeverage() methodTeaBuilder- Concrete builder for tea (50ml water, 60ml milk, 15g sugar, 30g tea powder)CoffeeBuilder- Concrete builder for coffee (40ml water, 50ml milk, 10g sugar, 15g coffee powder)
BeverageDirector beverageDirector = new BeverageDirector();
// Build Tea
TeaBuilder teaBuilder = new TeaBuilder();
Beverage tea = beverageDirector.MakeBeverage(teaBuilder);
Console.WriteLine(tea.ShowBeverage());
// Output: "Hot Tea [50 ml of water, 60ml of milk, 15 gm of sugar, 30 gm of Tea]"
// Build Coffee
CoffeeBuilder coffeeBuilder = new CoffeeBuilder();
Beverage coffee = beverageDirector.MakeBeverage(coffeeBuilder);
Console.WriteLine(coffee.ShowBeverage());
// Output: "Hot Coffee [40 ml of water, 50ml of milk, 10 gm of sugar, 15 gm of Coffee]"- Step 1: Boiling Water
- Step 2: Adding Milk
- Step 3: Adding Sugar
- Step 4: Adding Powder (Tea/Coffee)
- Step 5: Setting Beverage Type
- Allows you to construct objects step-by-step
- Can produce different representations using the same construction code
- Isolates complex construction code from business logic
- Follows Single Responsibility Principle
- Provides fine control over the construction process