As the name suggest the Builder pattern is used to gather complex objects so that the same construction process can be used to create different objects. It has the following parts:
- Builder – it is an interface / abstract class which the concrete builders implement. It has methods for assembling the product. It also has a method for retrieving the product object like GetProduct().
- Concrete Builders – The Concrete Builders implement the Builder interface and is responsible for creating and assembling the product. Each concrete builders have a different ways or creating and assembling product.
- Director – Director is responsible for construction of the product.
- Product – End product which gets constructed.
Let’s look at an example.
- Product – Main product which gets constructed.
public class Product
{
ArrayList al = new ArrayList();
public void Add(string part)
{
al.Add(part);
}
public void Show()
{
Console.WriteLine(“Product parts…”);
foreach (string str in al)
{
Console.WriteLine(str);
}
}
}
- Builder – IBuilder is the interface which all the concrete interfaces will implement and contains the methods for Building the product and getting the constructed product GetProduct().
public interface IBuilder
{
void BuildPartA();
void BuildPartB();
Product GetProduct();
}
- Concrete Builders – CarBuilder and TructBuilder implements the interface IBuilder and provides its own implementation for BuildPartA() and BuildPartB(). It maintains a Product object which is returned using GetProduct() method.
public class CarBuilder : IBuilder
{
private Product carProduct = new Product();
public override void BuildPartA()
{
carProduct.Add(“CarPartA”);
}
public override void BuildPartB()
{
carProduct.Add(“CarPartB”);
}
public override Product GetProduct()
{
return carProduct;
}
}
public class TruckBuilder : IBuilder
{
private Product tructProduct = new Product();
public override void BuildPartA()
{
tructProduct.Add(“TruckPartA”);
}
public override void BuildPartB()
{
tructProduct.Add(“TruckPartB”);
}
public override Product GetProduct()
{
return tructProduct;
}
}
- Director – This is the main class which contains the construction steps for building the product. It takes the IBuilder as an input parameter in the construction method so that based on the type of object created the respective builder class’s method will be executed. You can see how the Director is responsible for defining the steps for construction of the product and then returning the product.
public class Director
{
public Product ConstructProduct(IBuilder b)
{
b.BuildPartA();
b.BuildPartB();
return b.GetProduct();
}
}
- Client –
public static void Main()
{
Director director = new Director();
Builder car = new CarBuilder();
Builder truck = new TruckBuilder();
Product carProduct = director.ConstructProduct(car);
carProduct.Show();
Product tructProduct = director.ConstructProduct(truck);
tructProduct.Show();
}
No comments:
Post a Comment