Design Pattern articles in this series are listed below:

Design Patterns - An Overview
Design Patterns – Using the Strategy Pattern in C#
Design Patterns – Using the Singleton Pattern in C#
Design Patterns – Using the Adapter Pattern in C#
Design Patterns - Using the Facade Pattern in C#
Design Patterns - Using the Composite Pattern in C#
Design Patterns - Using the Decorator Pattern in C#
Design Patterns - Using the Abstract Factory Pattern in C#
Design Patterns – Using the Builder Pattern in C#
Design Patterns - Using the Observer Pattern in C# (Events and Delegates)
Design Patterns – Using the Chain of Responsibility Pattern in C#
Design Patterns – Using the State Pattern in C#
Design Patterns – Which to use When? Take the Quiz!

What is the Builder Pattern?

The Builder Pattern falls under the category of the Creational Patterns as it controls the instantiation of a class. This pattern is suitable in scenarios in which an object is made up several parts and the constituent parts need to be created in the same order using an algorithm. A real world example is in making a pizza. A pizza is made up of several parts (the crust, cheese and the toppings) that are constructed using an algorithm (bake the crust, add cheese and add the toppings).

The Builder pattern separates the specification of a complex object from its actual construction.

How is the Builder Pattern implemented?

The different players in the Builder Pattern are:

1. Director – A class that controls the algorithm that constructs the product. The client calls a method of the Director class that initiates the construction process.

2. IBuilder – An interface that defines the steps to be taken to construct the product

3. Builder1, Builder2.. BuilderN – Concrete Builder classes that implements how a product is constructed.

4. Product – A class that defines the type of the complex object that needs to be constructed

5. Client – The class that instantiates the director and builder objects and uses the product that is constructed

Let me explain the pattern using a real world example. Jane and Joe are two clients who are in the market for a new house. Jane likes to get a town home constructed and Joe likes a Single Family Home. They approach Bob the Contractor and put in their requests. Bob delegates the work to SubContractor1 who is an expert in building townhomes and SubContractor2 whose expertise is in building Single Family Homes.

Use Case Illustration

image 
JANE wants a Town Home

image

townhome  
  Sequence Diagram 1

 

image  
JOE wants a Single Family Home

image

 singlefamily  
  Sequence Diagram 2

Let’s map the players of the Builder Pattern to the roles in our example. Jane and Joe are Clients. Bob the Contractor is the Director and SubContractor1 and SubContractor2 are the concrete Builder classes. The House is the Product.

First, let’s look at the Director Class implementation. For simplicity, we are assuming that the house can be built by adding walls and a roof. The Town Home needs a small roof and 4 walls whereas the Single Family Home needs a large roof and 7 walls.

//Contractor (The Director class)
public class Contractor
{
    public void MakeHouse(ISubContractor contractor)
    {
        contractor.AddRoof();
        contractor.AddWalls();
    }
}

The SubContractor concrete classes implement an interface that has steps involved in building a house. There are 2 concrete Builder Classes – a TownHomeSubContractor and a SingleFamilyHomeSubContractor.

//Sub Contractor interface (IBuilder)
public interface ISubContractor
{
    void AddRoof();
    void AddWalls();
    House GetHouse();
}

//Concrete Builder Classes
public class TownHomeSubContractor : ISubContractor
{
    private House _house = new House();

    public void AddRoof()
    {
        _house.Roof = "Adding a small roof";
    }

    public void AddWalls()
    {
        _house.Walls = "Adding 4 Walls";
    }

    public House GetHouse()
    {
        return _house;
    }
}


public class SingleFamilySubContractor : ISubContractor
{
    private House _house = new House();

    public void AddRoof()
    {
        _house.Roof = "Adding a large roof";
    }

    public void AddWalls()
    {
        _house.Walls = "Adding 7 Walls";
    }

    public House GetHouse()
    {
        return _house;
    }
}

The Product (House) class is as shown below.

//Product Class
public class House
{
    public string Roof { get; set; }
    public string Walls { get; set; }
}

Finally, the Client that creates the Director and Builders and initiates the house building process.

namespace BuilderPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            //Jane wants a Town Home
            Console.WriteLine("Building a Town Home for Jane..");
            Contractor contractor = new Contractor();
            ISubContractor subContractorTownHome = new TownHomeSubContractor();
            contractor.MakeHouse(subContractorTownHome);
            House townHome = subContractorTownHome.GetHouse();
            Console.WriteLine(townHome.Roof + "..");
            Console.WriteLine(townHome.Walls + "..");

            //Joe wants a Single Family Home
            Console.WriteLine("\nBuilding a Town Home for Joe..");
            ISubContractor subContractorSingleFamily = new SingleFamilySubContractor();
            contractor.MakeHouse(subContractorSingleFamily);
            House singleFamilyHouse = subContractorSingleFamily.GetHouse();
            Console.WriteLine(singleFamilyHouse.Roof + "..");
            Console.WriteLine(singleFamilyHouse.Walls + "..");
        }
    }
}

The output simulates building the Town Home for Jane and a Single Family Home for Joe.

image

Physical Model – Class Diagram

image

Conclusion

The Builder Pattern can be used when the algorithm for creating parts is independent from the parts themselves. It gives a finer control on the construction process. At a high level, it is similar to the Abstract Factory Pattern. However, the Builder Pattern is the answer to how and the Abstract Factory Pattern is an answer to what.

Do not forget to read other Design Pattern articles. As always, you can follow DotNetCube on Twitter or subscribe to the RSS feed.

.

Retweetkick it on DotNetKicks.com