Luna Tech

Tutorials For Dummies.

Builder Pattern

2022-03-12


0. What is Builder Pattern?

Reference

Used to help use separate the construction of a complex object from its representation so that the same construction process can create different representations.


1. Implementation of Builder Pattern

Example Code

Components & Steps

  1. Define a class object - complex object
  2. Add a builder interface
  3. Create a concrete builder class
  4. Implement a director class
class Program
{
    static void Main(string[] args)
    {
        var items = new List<FurnitureItem>
        {
            new FurnitureItem("Sectional Couch", 55.5, 22.4, 78.6, 35.0),
            new FurnitureItem("Nightstand", 25.0, 12.4, 20.0, 10.0),
            new FurnitureItem("Dining Table", 105.0, 35.4, 100.6, 55.5),
        };

        // create an instance of the concrete class
        var inventoryBuilder = new DailyReportBuilder(items);
        // set up a director class
        var director = new InventoryBuilderDirector(inventoryBuilder);
        // use director to build the item
        director.CreateReport();
        // get the report from the concrete class
        var directorReport = inventoryBuilder.GetDailyReport();
        Console.WriteLine(directorReport.Debug());
    }
}

Fluent Variation (not require director class)

Example Code

  1. Define a class object - complex object
  2. Add a builder interface - note we need to change the interface signature
  3. Create a concrete builder class
class Program
{
    static void Main(string[] args)
    {
        var items = new List<FurnitureItem>
        {
            new FurnitureItem("Sectional Couch", 55.5, 22.4, 78.6, 35.0),
            new FurnitureItem("Nightstand", 25.0, 12.4, 20.0, 10.0),
            new FurnitureItem("Dining Table", 105.0, 35.4, 100.6, 55.5),
        };

        // create an instance of the concrete class
        var inventoryBuilder = new DailyReportBuilder(items);
        // call methods directly to build object
        // the fluent variation doesn't require a director class
        var fluentReport = inventoryBuilder
            .AddTitle()
            .AddDimensions()
            .AddLogistics(DateTime.UtcNow)
            .GetDailyReport();

        Console.WriteLine(fluentReport.Debug());
    }
}


Summary