Builder Design Pattern From Intent to Implementation

Introduction

The Builder Pattern is among the Creational Patterns of the Gang Of Four (GOF). To understand this pattern, we first need to understand its intent.

Intent

“Separate the construction of a complex object from its representation so that the same construction process can create different representations.” –GOF

The preceding definition of the Builder Design Pattern is given by the GOF. It might be difficult to understand by reading the definition, so let us understand it by dividing it up.



So the moral of the story is "Separate object construction from its representation".

Now let's understand the implementation of this pattern using a real-world scenario.

Scenario

On one fine day a Pizza vendor has placed an order to a software company. His requirement was to get the list of contents to make a Pizza based on the requested Pizza type. The company has accepted the order and has provided this definition to his Project Manager Mr. X. Then Mr. X has explained all the requirements to his developer Mr. Y and asked him to develop a program for that.



Approach 1

Mr. Y has begun thinking of the definition. He thought that there are many possible contents in a Pizza, like size, dough type, cheese type and so on. So first he created enumerations for all these selections. Then he created one class called "Pizza". In this class he has created a parameterized constructor with all required contents to create the Pizza. This constructor accepts the contents and sets the values in private variables. Now Mr. X has accept the functionality for the contents from the client, so he created a method called "PizzaContent" to print the entire list of contents to generate the Pizza.

  1. public class Pizza  
  2.     {  
  3.         private readonly DoughType doughType;  
  4.         private readonly bool isRedPepper;  
  5.         private readonly Size size;  
  6.         private readonly CheeseType cheeseType;  
  7.         private readonly List<string> vegetables;  
  8.           
  9.         public Pizza(DoughType doughType, bool isRedPepper, Size size,CheeseType cheeseType,List<string> vegetables)  
  10.         {  
  11.             this.doughType = doughType;  
  12.             this.isRedPepper = isRedPepper;  
  13.             this.size=size;  
  14.             this.cheeseType=cheeseType;  
  15.             this.vegetables=vegetables;  
  16.         }  
  17.           
  18.         public void PizzaContent()  
  19.         {  
  20.             Console.WriteLine("Pizza with {0}", doughType);  
  21.           
  22.             if (isRedPepper)  
  23.                 Console.WriteLine("Red Pepper");  
  24.               
  25.             Console.WriteLine("Size: {0}"size);  
  26.             Console.WriteLine("Cheese Type: {0}", cheeseType);  
  27.             Console.WriteLine("Vegetables:");  
  28.               
  29.             foreach (var item in vegetables)  
  30.             {  
  31.                 Console.WriteLine(" {0}", item);  
  32.             }  
  33.         }  
  34.     }  
  35.     public enum DoughType  
  36.     {  
  37.         Neapolitan_Pizza_Dough = 1,  
  38.         NewYorkStyle_Pizza_Dough = 2,  
  39.         SquarePan_Pizza_Dough = 3  
  40.     }  
  41.   
  42.     public enum CheeseType  
  43.     {  
  44.         American = 1,  
  45.         Swiss = 2,  
  46.     }  
  47.   
  48.     public enum Size  
  49.     {  
  50.         Small = 1,  
  51.         Medium = 2,  
  52.         Large = 3  
  53.     }  
Client-Side Code

Mr. Y has created an object of the Pizza class where he has provided the contents of his choice to create a Pizza and called the method to get the contents.
  1. static void Main(string[] args)  
  2.         {  
  3.             new Pizza(DoughType.Neapolitan_Pizza_Dough, true, Size.Medium, CheeseType.Swiss, new List<string> { "Tomato""Capsicum","Corn" }).PizzaContent();  
  4.             Console.ReadKey();  
  5.         }  
Output

Mr. Y has checked the application and it was built and run successfully.



Mr. Y was very happy that he has completed the given task successfully. He has provided the demo to his Project Manager Mr. X. Mr. X has gone through the application and has discovered a problem. The constructor is very large, in other words the constructor has many parameters. He asked Mr. Y to solve that problem.



Huge Constructor / Too many parameters

Approach 2

Again Mr. Y has started working on it. He has made some changes in the Pizza class. He has converted a variable into properties and removed the parameterized constructor.
  1. public class Pizza  
  2.     {  
  3.        public DoughType doughType {getset;}  
  4.        public bool isRedPepper { getset; }  
  5.        public Size size { getset; }  
  6.        public CheeseType cheeseType { getset; }  
  7.        public List<string> vegetables { getset; }  
  8.          
  9.         public void PizzaContent()  
  10.         {  
  11.             Console.WriteLine("Pizza with {0}", doughType);  
  12.             if (isRedPepper)  
  13.                 Console.WriteLine("Red Pepper");  
  14.             Console.WriteLine("Size: {0}", size);  
  15.             Console.WriteLine("Cheese Type: {0}", cheeseType);  
  16.             Console.WriteLine("Vegetables:");  
  17.             foreach (var item in vegetables)  
  18.             {  
  19.                 Console.WriteLine(" {0}", item);  
  20.             }  
  21.         }  
  22.     }  
  23.   
  24.     public enum DoughType  
  25.     {  
  26.         Neapolitan_Pizza_Dough = 1,  
  27.         NewYorkStyle_Pizza_Dough = 2,  
  28.         SquarePan_Pizza_Dough = 3  
  29.     }  
  30.   
  31.     public enum CheeseType  
  32.     {  
  33.         American = 1,  
  34.         Swiss = 2,  
  35.     }  
  36.   
  37.     public enum Size  
  38.     {  
  39.         Small = 1,  
  40.         Medium = 2,  
  41.         Large = 3  
  42.     }  
Client-Side Code

Mr. Y has created an object of the Pizza class and has set all the properties for that object and called the method.
  1. static void Main(string[] args)  
  2.       {  
  3.           var pizza = new Pizza();  
  4.           pizza.doughType = DoughType.Neapolitan_Pizza_Dough;  
  5.           pizza.isRedPepper = true;  
  6.           pizza.size = Size.Large;  
  7.           pizza.cheeseType = CheeseType.American;  
  8.           pizza.vegetables = new List<string> { "Tomato""Corn" };  
  9.   
  10.           pizza.PizzaContent();  
  11.   
  12.           Console.ReadKey();  
  13.       }  
Output

Mr. Y has built and run the application again.



This time Mr. Y thought that he has solved the problem. He has shown the application to his Project Manager Mr. X. Mr. X was a little happy but explained that the client needs to remember all the properties, so you need to figure out some solution.



Need to remember all the properties

Approach 3

Mr. Y has again started working on that and he got the solution for not remembering the properties. This time he didn't change anything in the Pizza class.
  1. public class Pizza  
  2.     {  
  3.        public DoughType doughType {getset;}  
  4.        public bool isRedPepper { getset; }  
  5.        public Size size { getset; }  
  6.        public CheeseType cheeseType { getset; }  
  7.        public List<string> vegetables { getset; }  
  8.          
  9.         public void PizzaContent()  
  10.         {  
  11.             Console.WriteLine("Pizza with {0}", doughType);  
  12.             if (isRedPepper)  
  13.                 Console.WriteLine("Red Pepper");  
  14.             Console.WriteLine("Size: {0}", size);  
  15.             Console.WriteLine("Cheese Type: {0}", cheeseType);  
  16.             Console.WriteLine("Vegetables:");  
  17.             foreach (var item in vegetables)  
  18.             {  
  19.                 Console.WriteLine(" {0}", item);  
  20.             }  
  21.         }  
  22.     }  
  23.     public enum DoughType  
  24.     {  
  25.         Neapolitan_Pizza_Dough = 1,  
  26.         NewYorkStyle_Pizza_Dough = 2,  
  27.         SquarePan_Pizza_Dough = 3  
  28.     }  
  29.   
  30.     public enum CheeseType  
  31.     {  
  32.         American = 1,  
  33.         Swiss = 2,  
  34.     }  
  35.   
  36.     public enum Size  
  37.     {  
  38.         Small = 1,  
  39.         Medium = 2,  
  40.         Large = 3  
  41.     }  
Mr. Y has created a new class "MyPizzaBuilder". In this class he has implemented the following three major things:
  1. Create one method "GetPizza" that returns an instance of a Pizza class
  2. Create methods ("PrepareDough", "AppyVegetables", "AppyCheese", "AddCondiments") to set properties
  3. Create one more method "CreatePizza" that initializes an object of the Pizza class and calls the preceding methods
  1. public class MyPizzaBuilder  
  2.     {  
  3.         Pizza pizza;  
  4.   
  5.         public Pizza GetPizza()  
  6.         {  
  7.             return pizza;  
  8.         }  
  9.   
  10.         public void CreatePizza()  
  11.         {  
  12.             pizza = new Pizza();  
  13.   
  14.             PrepareDough();  
  15.             ApplyVegetables();  
  16.             ApplyCheese();  
  17.             AddCondiments();  
  18.         }  
  19.   
  20.         private void AddCondiments()  
  21.         {  
  22.             pizza.isRedPepper = true;  
  23.         }  
  24.   
  25.         private void ApplyCheese()  
  26.         {  
  27.             pizza.cheeseType = CheeseType.American;  
  28.         }  
  29.   
  30.         private void ApplyVegetables()  
  31.         {  
  32.             pizza.vegetables = new List<string> { "Tomato""Corn" };  
  33.         }  
  34.   
  35.         private void PrepareDough()  
  36.         {  
  37.             pizza.doughType = DoughType.Neapolitan_Pizza_Dough;  
  38.             pizza.size = Size.Large;  
  39.         }  
  40.     }  
Client-Side Code
 
In the client side Mr. Y has created an object of the "MyPizzaBuilder" class and called the "CreatePizza" method. As we have seen the "CreatePizza" method calls all the methods that are required to set the properties. So in this way the client does not need to remember all the properties.
  1. static void Main(string[] args)  
  2.         {  
  3.             var builder = new MyPizzaBuilder();  
  4.             builder.CreatePizza();  
  5.            var pizza = builder.GetPizza();  
  6.             pizza.PizzaContent();  
  7.   
  8.             Console.ReadKey();  
  9.         }  
Output

Again Mr. Y has built and run the application and was very happy. He just explained the solution to his Project Manager. The Project Manager appreciated his efforts and asked one question "What if we want to create another type of Pizza?" Mr. Y was realized that he must copy "MyPizzaBuilder" and then change the definition of creating a Pizza.





If you want to create another type of Pizza then you need to create another class and copy from MyPizzaBuilder and change the definition of creating a Pizza. This is not a good practice.

Approach 4

Mr. Y has become fed up with the situation and this time he just wants a concrete solution. So he has thought about it and came up with the solution. In this approach he also didn't change anything in the "Pizza" class.
  1. public class Pizza  
  2.     {  
  3.        public DoughType doughType {getset;}  
  4.        public bool isRedPeeper { getset; }  
  5.        public Size size { getset; }  
  6.        public CheeseType cheeseType { getset; }  
  7.        public List<string> vegetables { getset; }  
  8.          
  9.         public void PizzaContent()  
  10.         {  
  11.             Console.WriteLine("Pizza with {0}", doughType);  
  12.             if (isRedPeeper)  
  13.                 Console.WriteLine("Red Peeper");  
  14.             Console.WriteLine("Size: {0}", size);  
  15.             Console.WriteLine("Cheese Type: {0}", cheeseType);  
  16.             Console.WriteLine("Vegetables:");  
  17.             foreach (var item in vegetables)  
  18.             {  
  19.                 Console.WriteLine(" {0}", item);  
  20.             }  
  21.         }  
  22.     }  
  23.     public enum DoughType  
  24.     {  
  25.         Neapolitan_Pizza_Dough = 1,  
  26.         NewYorkStyle_Pizza_Dough = 2,  
  27.         SquarePan_Pizza_Dough = 3  
  28.     }  
  29.   
  30.     public enum CheeseType  
  31.     {  
  32.         American = 1,  
  33.         Swiss = 2,  
  34.     }  
  35.   
  36.     public enum Size  
  37.     {  
  38.         Small = 1,  
  39.         Medium = 2,  
  40.         Large = 3  
  41.     }  
This time he has created an abstract class "PizzaBuilder" and declared all the methods that were used to set the properties as abstract.
  1. public abstract class PizzaBuilder  
  2.     {  
  3.         protected Pizza pizza;  
  4.   
  5.         public Pizza GetPizza()  
  6.         {  
  7.             return pizza;  
  8.         }  
  9.   
  10.         public void CreateNewPizza()  
  11.         {  
  12.             pizza = new Pizza();  
  13.         }  
  14.   
  15.         public abstract void PrepareDough();  
  16.         public abstract void ApplyVegetables();  
  17.         public abstract void ApplyCheese();  
  18.         public abstract void AddCondiments();  
  19.     }  
Mr. Y has inherited the preceding abstract class into "MyPizzaBuilder" and implemented all the abstract methods. So in this way he has a solution and implemented it. Now if the client wants to create another type of pizza then he must inherit the same abstract class and implement the properties.
  1. public class MyPizzaBuilder : PizzaBuilder  
  2.     {  
  3.         public override void AddCondiments()  
  4.         {  
  5.             pizza.isRedPeeper = true;  
  6.         }  
  7.   
  8.         public override void ApplyCheese()  
  9.         {  
  10.             pizza.cheeseType = CheeseType.American;  
  11.         }  
  12.   
  13.         public override void ApplyVegetables()  
  14.         {  
  15.             pizza.vegetables = new List<string> { "Tomato""Corn" };  
  16.         }  
  17.   
  18.         public override void PrepareDough()  
  19.         {  
  20.             pizza.doughType = DoughType.Neapolitan_Pizza_Dough;  
  21.             pizza.size = Size.Large;  
  22.         }  
  23.     }  
Mr. Y has created one more class, "PizzaMaker", to construct an object using the builder abstract class. So in this class the client must pass a builder and the methods are called of that specific concrete builder.
  1. public class PizzaMaker  
  2. {  
  3.     private readonly PizzaBuilder builder;  
  4.   
  5.     public PizzaMaker(PizzaBuilder builder)  
  6.     {  
  7.         this.builder = builder;  
  8.     }  
  9.   
  10.     public void BuildPizza()   
  11.     {  
  12.         builder.CreateNewPizza();  
  13.         builder.PrepareDough();  
  14.         builder.ApplyVegetables();  
  15.         builder.ApplyCheese();  
  16.         builder.AddCondiments();  
  17.     }  
  18.   
  19.     public Pizza GetPizza()   
  20.     {  
  21.         return builder.GetPizza();  
  22.     }  
  23. }  
Let's check what Mr. Y has done so far using a Class Diagram. Mr. Y has created the "Pizza" class that was our product. Then he created a "PizzaBuilder" abstract class that was our builder. Then he has created two concrete builders, in other words "MyPizzaBuilder" and "TomatoPizzaBuilder". In the future the client can also add more concrete builders, in other words more types of Pizzas. Finally he has created the "PizzaMaker" class that was our director.



Participants
  • Builder (PizzaBuilder): Specifies an abstract interface for creating parts of a Product object.
  • ConcreteBuilder (MyPizzaBuilder, TomatoPizzaBuilder): Constructs and assembles parts of the product by implementing the Builder interface and defines and keeps track of the representation it creates. Provides an interface for retrieving the product.
  • Director (PizzaMaker): Constructs an object using the Builder interface.
  • Product (Pizza): Represents the complex object under construction. ConcreteBuilder builds the product's internal representation and defines the process by which it's assembled includes classes that define the constituent parts, including interfaces for assembling the parts into the final result.
Client-Side Code

In the client-side code Mr. Y has created an object of the "PizzaMaker" class and passed a "MyPizzaBuilder" object. Then he called the BuildPizza method that calls all the necessary methods to create a Pizza for that builder. In the third step he called the GetPizza method followed by the PizzaContent method. The same was done for "TomatoPizzaBuilder" also.
  1. static void Main(string[] args)  
  2.         {  
  3.             var pizzaMaker = new PizzaMaker(new MyPizzaBuilder());  
  4.             pizzaMaker.BuildPizza();  
  5.             var pizza1 = pizzaMaker.GetPizza();  
  6.   
  7.             pizza1.PizzaContent();  
  8.   
  9.             pizzaMaker = new PizzaMaker(new TomatoPizzaBuilder());  
  10.             pizzaMaker.BuildPizza();  
  11.             var pizza2 = pizzaMaker.GetPizza();  
  12.   
  13.             pizza2.PizzaContent();  
  14.   
  15.             Console.ReadKey();  
  16.         }  
Output

Mr. Y has built and run the application and gave the demo to Mr. X.



This time Mr. X has gone through the application and was very happy as Mr Y. has implemented "The Builder Design Pattern".



Summary

When we have multiple parameters, the order of those parameters are important and when we have different constructions, we should need to separate the construction of an object from its representation.