Design Patterns - The Builder Pattern



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


Design Patterns - Factory Method Pattern



So What is a Factory Method?

The Factory method is another Creational pattern. It's basically concerned with newing up your objects. It might be that you create a lot of FordFiesta objects and quite a lot of FordFocus objects. You might create these all over your program. Then something happens and you make a change to one of the types. This might lead to you having to go through and update every piece of code where you've gone var car = new FordFocus()

Why do I need a Factory Method?

There's a lot of duplication in all those new Cars. To remove the code duplication and therefore improve encapsulation we can defer all object creation of to a Factory specifically maybe a particular Factory Method for example FordFiestaFactory.CreateCar().

This also means that everyone only need depend on the abstraction, which makes eveything just that little more flexible.

Factory Method at a glance

Factory Method Code Examples

 

namespace FactoryMethod
{
    public class FordFiestaCarFactory : ICarFactory
    {
        public ICar CreateCar()
        {
            return new FordFiesta();
        }
    }
}

Above is the Factory itself, with the program using it shown below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FactoryMethod
{
    class Program
    {
        Program(ICarFactory carFactory)
        {                 
            var car = carFactory.CreateCar();
            car.Drive();            
        }


        static void Main(string[] args)
        {
            new Program(new FordFiestaCarFactory());
            new Program(new FordFocusCarFactory());
            Console.WriteLine("--------------");
            Console.ReadLine();
        }
    }


}

Recommended Reading

As before in my Abstract Factory post I'd recommend Head First Design Patterns as a really understandable guide to design patterns.

Downloads


Search

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2013