Quick Start on Builder Design Pattern

Background

One of the frequently used Creational patterns is the Builder Design pattern. This pattern simplifies building a complex object using a simple object with step-by-step approaches.

Real-world Analogy

Let’s put technical terminology aside and understand the common terms.

If you look around the real world, there are a lot of examples that will help you to learn about Builder Pattern.

  1. Preparing a Tea with basic necessary things like Water, Milk, Sugar, and Tea powder.
  2. Preparing a combo meal like North Indian meals and South Indian meals
  3. Building a mobile phone with Screen, Keypad, Battery, Camera, and IR sensor.
  4. Mc Donald meal pack with Veg/Non-Veg Burger, French fries, Coke, and toys.
  5. A house with Wall, Roof, Window, and Door.

And many more. If something is unique, please do post it in a comment box.

Example with Illustration

Let’s consider building a new car with the following different components like Body of car, Engine, Transmission system, Staring system, Door, Suspension, and more. All these components are assembled step-by-step with defined sequence order to build a car.

Quick Start on Builder Design Pattern

When can we use the Builder design pattern?

  • Build a complex object using a simple object with step-by-step approaches
  • Produce different types and representations of an object using the same construction code.

Pros

  • Construct objects step-by-step, run steps recursively.
  • Reuse the same construction code when building various representations of products
  • Isolate complex construction code from the business logic of the product.
  • Encapsulates code for construction and representation

Cons

  • Builder classes must be mutable.
  • May complicate dependency injection.

UML Representation

Quick Start on Builder Design Pattern

Code example: Let’s Build a Vehicle with required components

In the above UML diagram, let’s consider ‘VehicleCreator’ as a ‘Director’ to build the Vehicle with all the components step-by-step.

‘IVehicleBuilder’ as a ‘Builder’ to define the signature of individual components to build like BuildEngine(), BuildTransmission(), BuildDoor(), BuildBody() and many more.

‘TataHexaVehicle’ as a ‘ConcreteBuilder’ to define the implementation of each component to build a final product.

Define ‘Director’, Here Director as a ‘VehicleCreator’ to build the vehicle, the function CreateVehicle() defines the building of each component step-by-step.

namespace DP.BuilderPattern.Director
{
    using DP.BuilderPattern.Builder;
    using DP.BuilderPattern.Product;

    public class VehicleCreator
    {
        private IVehicleBuilder _vehicleBuilder;
        public VehicleCreator(IVehicleBuilder vehicleBuilder)
        {
            _vehicleBuilder = vehicleBuilder;
        }

        public void CreateVehicle()
        {
            _vehicleBuilder
                .BuildEngine()
                .BuildTransmission()
                .BuildBody()
                .BuildDoor()
                .BuildAccessories();
        }

        public Vehicle GetVehicle()
        {
            return _vehicleBuilder.GetProduct();
        }
    }
}

Define ‘Builder’. Here Builder is a ‘IVehicleBuilder’ that defines the signature of building components like BuildEngine(), BuildTransmission(), BuildDoor(), BuildBody() and BuildAccessories()

namespace DP.BuilderPattern.Builder
{
    using DP.BuilderPattern.Product;

    /// <summary>
    /// Interace for builder
    /// </summary>
    public interface IVehicleBuilder
    {
        /// <summary>
        /// Build Engine for Vehicle
        /// </summary>
        /// <returns>IVehicleBuilder</returns>
        IVehicleBuilder BuildEngine();

        /// <summary>
        /// Build Transmission system
        /// </summary>
        /// <returns>IVehicleBuilder</returns>
        IVehicleBuilder BuildTransmission();

        /// <summary>
        /// Build Door
        /// </summary>
        /// <returns>IVehicleBuilder</returns>
        IVehicleBuilder BuildDoor();

        /// <summary>
        /// Build Accessories
        /// </summary>
        /// <returns>IVehicleBuilder</returns>
        IVehicleBuilder BuildAccessories();

        /// <summary>
        /// Build Body
        /// </summary>
        /// <returns>IVehicleBuilder</returns>
        IVehicleBuilder BuildBody();

        /// <summary>
        /// Get product
        /// </summary>
        /// <returns>Vehicle</returns>
        Vehicle GetProduct();
    }
}

Define ‘Product’, Here Product is a ‘Vehicle’ that acts as a model class.

namespace DP.BuilderPattern.Product
{
    using System;
    using System.Collections.Generic;

    public class Vehicle
    {
        public string Model { get; set; }

        public string Name { get; set; }

        public string Engine { get; set; }

        public string Transmission { get; set; }

        public string Body { get; set; }

        public int Door { get; set; }

        public List<string> Accessories { get; set; }

        public Vehicle()
        {
            Accessories = new List<string>();
        }

        public void DisplayDetails()
        {
            Console.WriteLine("Model: " + Model);
            Console.WriteLine("Name: " + Name);
            Console.WriteLine("Transmission: " + Transmission);
            Console.WriteLine("Body: " + Body);
            Console.WriteLine("Door: " + Door);
            Console.WriteLine("Accessories: " + string.Join(", ", Accessories));
        }
    }
}

Define ‘ConcreteBuilder’, Here ConcreteBuilder as a ‘TataHexaVehicle’ defines the implementation of each component like Engine, Transmission system, Body, Door, and Accessories.

namespace DP.BuilderPattern.ConcreteBuilder
{
    using DP.BuilderPattern.Builder;
    using DP.BuilderPattern.Product;

    public sealed class TataHexaVehicle : IVehicleBuilder
    {
        private Vehicle _Vehicle = null;

        public TataHexaVehicle(string model)
        {
            _Vehicle = new Vehicle();
            _Vehicle.Name = "Hexa";
            _Vehicle.Model = model;
        }
        public IVehicleBuilder BuildAccessories()
        {
            _Vehicle.Accessories.Add("Seat Cover");
            _Vehicle.Accessories.Add("Rear Mirror");
            _Vehicle.Accessories.Add("Foot light");
            _Vehicle.Accessories.Add("Rear Camera");
            return this;
        }

        public IVehicleBuilder BuildBody()
        {
            _Vehicle.Body = "Jet Alloy";
            return this;
        }

        public IVehicleBuilder BuildDoor()
        {
            _Vehicle.Door = 5;
            return this;
        }

        public IVehicleBuilder BuildEngine()
        {
            _Vehicle.Engine = "2.0L";
            return this;
        }

        public IVehicleBuilder BuildTransmission()
        {
            _Vehicle.Transmission = "4D";
            return this;
        }

        public Vehicle GetProduct()
        {
            return _Vehicle;
        }
    }
}

Program Execution

  • Create an instance of Vehicle creator with Tata Hexa Car type.
  • Build the Vehicle with all the component by calling CreateVehicle()
namespace DP.BuilderPattern
{
    using System;
    using DP.BuilderPattern.ConcreteBuilder;
    using DP.BuilderPattern.Director;

    public class Program
    {
        public static void Main(string[] args)
        {
            VehicleCreator vehicleCreator = new VehicleCreator(new TataHexaVehicle("2020"));
            vehicleCreator.CreateVehicle();
            vehicleCreator.GetVehicle().DisplayDetails();
            Console.ReadLine();
        }
    }
}

Output

Here we are able to see how the vehicle has been built with all sets of components in step-by-step approaches. Builder design pattern simplifies building an object with the required defined sequences.

I hope this article helps you to understand this simple approach. Thanks for reading the article.


Similar Articles