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();
}
}
- 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?
- 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
Aucun commentaire:
Enregistrer un commentaire