Builder Pattern

From Logic Wiki
Jump to: navigation, search


Separate the construction of a complex object from its representation, so you can build it step by step and in different ways.

What problem it solves

When an object:

  • has many optional parameters
  • needs to be created in specific steps
  • or has multiple valid configurations

…constructors get ugly fast.

public class House
{
    public int Floors { get; set; }
    public bool HasGarage { get; set; }
    public bool HasGarden { get; set; }
}

public class HouseBuilder
{
    private readonly House _house = new House();

    public HouseBuilder WithFloors(int floors)
    {
        _house.Floors = floors;
        return this;
    }

    public HouseBuilder WithGarage()
    {
        _house.HasGarage = true;
        return this;
    }

    public HouseBuilder WithGarden()
    {
        _house.HasGarden = true;
        return this;
    }

    public House Build() => _house;
}

Usage

House house = new HouseBuilder()
    .WithFloors(2)
    .WithGarage()
    .Build();