Builder Creational Pattern separates the process of construction of a complex object from its actual representation. This means that the same process can create different representations of same object.
Consider the following diagram :
The main class here is ShapeCreator which is called Director and controls the process of construction of object.
// Director
public class ShapeCreator
{
public void CreateSquare(SquareBuilder sb)
{
sb.Create();
sb.SetColor();
}
}
While Square is the actual object. RedSquareBuilder controls the actual representation of the object.
Consider the following client code :
public class Client
{
ShapeCreator d;
public void Run()
{
d = new ShapeCreator(); //Director
SquareBuilder sb = new RedSquareBuilder();
d.CreateSquare(sb);
Square sq;
sq = sb.GetSquare();
Console.WriteLine(sq.Color + " Color Square created");
}
}
Just by changing the instance value of SquareBuilder, another representation of Square can be created by ShapeCreator.
Download full source code from here : Builder Creational Pattern source code
No comments:
Post a Comment