Sobes.tech
Middle

What is the 'Builder' design pattern and in which cases is it best to use?

sobes.tech AI

Answer from AI

Builder is a creational design pattern that allows constructing complex objects step by step. It separates the construction of a complex object from its representation, enabling the same construction process to create different representations of the object.

Main components of the pattern:

  • Builder: An interface that defines operations for constructing parts of the object.
  • Concrete Builder: Implements the Builder interface and constructs and assembles parts of the product.
  • Director: A class that uses the Builder to construct the object. It defines the order of calling construction steps.
  • Product: The complex object that is constructed with the Builder.

It is best used in cases where:

  • The process of creating a complex object should be independent of the parts that make up the object and how they are assembled.
  • There is a need to create different representations of the same object using the same construction process.
  • The constructor of the object has too many parameters.

Example:

// Builder interface
public interface ICarBuilder
{
    void BuildEngine();
    void BuildWheels();
    void BuildBody();
    Car GetCar();
}

// Concrete Builder
public class SportCarBuilder : ICarBuilder
{
    private Car _car = new Car();

    public void BuildEngine()
    {
        _car.Engine = "Sport Engine";
    }

    public void BuildWheels()
    {
        _car.Wheels = "Sport Wheels";
    }

    public void BuildBody()
    {
        _car.Body = "Sport Body";
    }

    public Car GetCar()
    {
        return _car;
    }
}

// Product
public class Car
{
    public string Engine { get; set; }
    public string Wheels { get; set; }
    public string Body { get; set; }

    public void Show()
    {
        Console.WriteLine($"Car built: Engine={Engine}, Wheels={Wheels}, Body={Body}");
    }
}

// Director
public class Director
{
    private ICarBuilder _builder;

    public Director(ICarBuilder builder)
    {
        _builder = builder;
    }

    public void ConstructSportCar()
    {
        _builder.BuildEngine();
        _builder.BuildWheels();
        _builder.BuildBody();
    }
}

// Client code
public class Client
{
    public static void Main(string[] args)
    {
        ICarBuilder builder = new SportCarBuilder();
        Director director = new Director(builder);

        director.ConstructSportCar();
        Car sportCar = builder.GetCar();
        sportCar.Show();
    }
}