- Posted by dan on August 12, 2011
What's the builder pattern?
The builder pattern is a way to encapsulate the way in which you build a Car in our example and allow it to be created in steps.
Imagine the scenario where you allow customers to customise the car they're buying. Some people might want a red car with a sunroof others might want a SatNav others might want an Alarm. This makes creating our car objects a bit tricky.
Builder Pattern Diagram

Builder Pattern Example Code
using System;
namespace Builder
{
class Program
{
static void Main(string[] args)
{
var fordFiesta = new FordFiestaBuilder()
.AddAlarm(true)
.AddDoors(5)
.AddSatNav(true)
.AddEngine("2.8")
.CarBody("Convertible")
.PaintColor("Red")
.AddSatNav(true)
.AddSunroof(true)
.Mp3Player(true)
.Build();
Console.WriteLine(fordFiesta);
Console.ReadLine();
}
}
}
Now below please notice that we're essentally using the Fluent builder pattern, which is increasingly used when configuring things like Nhibernate and other frameworks. The magic is shown below, and it's as simple as returning this as in the current object. The final Build() method returns our Car object and we're off.
namespace Builder
{
public abstract class CarBuilder
{
protected string _make;
protected string _model;
protected bool _mp3Player;
protected string _carBody;
protected string _colour;
protected int _numberOfDoors;
protected string _engineSize;
protected bool _sunroof;
protected bool _satNav;
protected bool _alarm;
public CarBuilder Make(string make)
{
_make = make;
return this;
}
public CarBuilder Model(string model)
{
_model = model;
return this;
}
public CarBuilder AddAlarm(bool alarm)
{
_alarm = alarm;
return this;
}
public CarBuilder AddSatNav(bool satNav)
{
_satNav = satNav;
return this;
}
public CarBuilder AddSunroof(bool sunroof)
{
_sunroof = sunroof;
return this;
}
public CarBuilder Mp3Player(bool mp3Player)
{
_mp3Player = mp3Player;
return this;
}
public CarBuilder CarBody(string carBody)
{
_carBody = carBody;
return this;
}
public CarBuilder PaintColor(string colour)
{
_colour = colour;
return this;
}
public CarBuilder AddDoors(int numberOfDoors)
{
_numberOfDoors = numberOfDoors;
return this;
}
public CarBuilder AddEngine(string engineSize)
{
_engineSize = engineSize;
return this;
}
public Car Build()
{
return new Car(_make, _model, _mp3Player, _carBody, _colour, _numberOfDoors, _engineSize, _sunroof, _satNav,
_alarm);
}
}
}
Recommended Reading
I'd recommend the GoF Design patterns : elements of reusable object-oriented software
over the Head First Design Patterns book in this case, I think it simply had more information.


Downloads
References