Pages

Friday, March 3, 2017

Builder pattern

The builder pattern is an object creation software design pattern. Unlike the abstract factory pattern and the factory method pattern whose intention is to enable polymorphism, the intention of the builder pattern is to find a solution to the telescoping constructor anti-pattern. The telescoping constructor anti-pattern occurs when the increase of object constructor parameter combination leads to an exponential list of constructors. Instead of using numerous constructors, the builder pattern uses another object, a builder, that receives each initialization parameter step by step and then returns the resulting constructed object at once.


Definition

The intent of the Builder design pattern is to separate the construction of a complex object from its representation. By doing so the same construction process can create different representations. [2]

Advantages

<![if !supportLists]>·        <![endif]>Allows you to vary a product’s internal representation.
<![if !supportLists]>·        <![endif]>Encapsulates code for construction and representation.
<![if !supportLists]>·        <![endif]>Provides control over steps of construction process.

Disadvantages               

<![if !supportLists]>·        <![endif]>Requires creating a separate ConcreteBuilder for each different type of Product.

Structure

Builder
Abstract interface for creating objects (product).
ConcreteBuilder
Provides implementation for Builder. It is an object able to construct other objects. Constructs and assembles parts to build the objects.



/// <summary>
/// Represents a product created by the builder
/// </summary>
public class Car
{
    public Car()
    {
    }

    public int Wheels { get; set; }

    public string Colour { get; set; }
}

/// <summary>
/// The builder abstraction
/// </summary>
public interface ICarBuilder
{
    // Adding NotNull attribute to prevent null input argument
    void SetColour([NotNull]string colour);

    // Adding NotNull attribute to prevent null input argument
    void SetWheels([NotNull]int count);

    Car GetResult();
}

/// <summary>
/// Concrete builder implementation
/// </summary>
public class CarBuilder : ICarBuilder
{
    private Car _car;

    public CarBuilder()
    {
        this._car = new Car();
    }

    public void SetColour(string colour)
    {
        this._car.Colour = colour;
    }

    public void SetWheels(int count)
    {
        this._car.Wheels = count;
    }

    public Car GetResult()
    {
        return this._car;
    }
}

/// <summary>
/// The director
/// </summary>
public class CarBuildDirector
{
    public Car Construct()
    {
        CarBuilder builder = new CarBuilder();

        builder.SetColour("Red");
        builder.SetWheels(4);

        return builder.GetResult();
    }
}
The Director assembles a car instance in the example above, delegating the construction to a separate builder object.