0

Wikipedia States that

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[citation needed]. 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.

And gives the following example

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

    public int Wheels { get; set; }

    public string Colour { get; set; }
}

//The builder abstraction
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();
}

//Concrete builder implementation
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;
    }
}

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

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

        return builder.GetResult();
    }
}
  1. This just seem an unnecessary redirection.why cant one without using CarBuilder() directly initialize a car object and set its properties directly.what is the advantage of using carbuilder in this code snippet?
  2. is builder patterns intention only to avoid telescoping constructor anti-pattern? if that is so it just seem unnecessary work because one can directly set properties using getters and setters
user119020
  • 413
  • 1
  • 3
  • 13
  • Possible duplicate of [When would you use the Builder Pattern?](http://stackoverflow.com/questions/328496/when-would-you-use-the-builder-pattern) – jaco0646 May 20 '16 at 12:12

2 Answers2

0

The example given by example does not show the real advantage of the builder pattern. Consider a class like this :

public class Demo{
    private Integer i;
    private Short s;
    private String str;
    private Double d;
    private Float f;
    private Boolean b;
    private Byte by;

    public Demo(Integer i, Short s, String str, Double d, Float f, Boolean b, Byte b){
        //setting all members ommited...
    }


    public Demo(Short s, String str, Double d, Float f, Boolean b, Byte by){
        this(null, s, str, d, f, b, by);
    }

    public Demo(Integer i,  String str, Double d, Float f, Boolean b, Byte b){
        this(i, null, str, d, f, b, by);
    }

    public Demo(Integer i){
        this(i, "Very short constructor", null, null, null, null);
    }

}

There are already 4 constructors and there could be many more. Also the constructors are delegating to the "base" constructor.

But you can delete every but one constructor if you use a builder pattern.

public class DemoBuilder{
    private Integer i=INTEGER_DEFAULT;
    private Short s = SHORT_DEFAULT;
    private String str=STRING_DEFAULT;
    private Double d=DOUBLE_DEFAULT;
    private Float f=FLOAT_DEFAULT;
    private Boolean b=BOOLEAN_DEFAULT;
    private Byte by=BYTE_DEFAULT;

    public void setStr(String str){
        this.str=str;
    }

    //more setters

    public Demo build(){
        return new Demo(i,s,str,d,f,b,by);
    }
}

Also now you don't need the docs to identify the semantics of the different constructors and their parameters. You have a builder where each setter has a meaningful name. In my example thats just setStr, but in a more realistic example that would be something like setServerName.

All in all:

  1. There are situations where you need a lot of parameters during object creation. I remember a situation where a class needed 4 strategies and a few more parameters. Since non of them would change during the objects lifecycle they were obvious candidates fore final members. But the constructor looked like public MyClass(IStrategy doBefore, IStrategy doAfter, IStrategy doInBetween, IStrategy doOnException, String name, int priority, MyEnum anotherEnumConstant). Even though it had only one constructor a builder simplified object creation.
  2. The builder pattern also converts parameter order into named methods. Thats a cleaner approach.
samjaf
  • 1,033
  • 1
  • 9
  • 19
0

Beware of unsourced statements in Wikipedia articles. If you pay attention, right where there is [citation needed] in your excerpt, the tooltip says :

Needs a reliable source. The Go4 pattern describes a different purpose for the pattern.

Indeed, the original pattern is more along the lines of the Definition a few lines below in the Wikipedia article :

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.

The Go4 book explicitly states that the purpose of Builder is to have different flavors of construction. It involves an abstract Builder that defines the contract of how you can build the final object, and concrete Builder subclasses. All examples in the book include abstract classes and concrete subclasses, such as StandardMazeBuilder, CountingMazeBuilder, etc. The Wikipedia code sample you gave doesn't, which makes it less relevant IMO.

guillaume31
  • 13,738
  • 1
  • 32
  • 51