Saturday, November 13, 2010

..........Builder Pattern[CD]

The Builder Design Pattern separates the creation of an instance of a class from its representation so that the same creation pattern can be used for creating different representations of the object.

The Builder Pattern separates the construction of a complex object from its representation so that the same construction process can create different representations. - Gof

A Builder can be one of implementations of the AbstractFactory. Of course it can use other factories to build the parts of its product.

The idea behind the builder pattern is to create a complex or multipart object on behalf of a client which knows the object to be created but does not know how it is being put together. It is applicable when the object cannot be created in an arbitrary manner. It helps the construction process to meet these requirements:

* There are several steps used to create the parts which make up the complex object
* These steps need to be carried out in a particular sequence.
* The product instantiation process must be hidden from the client.


The BuilderPattern is similar to FactoryPattern, but creates a complex object using a number of steps.

Example: DocumentBuilderFactory, StringBuffer, StringBuilder are some examples of builder pattern.


Example:

Build a complex object step by step:-

class Figure
{
public abstract DrawFigure();
public abstract DrawShade();
public abstract FillColor();
}

public Circle : Figure
{
private override DrawFigure()
{
Console.Writeline(“Draw Circle”);
}

private override DrawShade()
{
Console.Writeline(“Draw Shade”);
}


private override FillColor()
{
Console.Writeline(“Fill Red Color ”);
}
}


public Rectangle : Figure
{
private override DrawFigure()
{
Console.Writeline(“Draw Rectangle”);
}

private override DrawShade()
{
Console.Writeline(“Draw Shade”);
}


private override FillColor()
{
Console.Writeline(“Fill Green Color ”);
}
}

class Shape
{
public void CreateFigure(Figure objFigure)
{
objFigure.DrawFigure();
objFigure.DrawShade();
objFigure.FillColor();
}
}

public static void main(String[] args)
{

Figure objFigure=null;
Shape objShape=null;
objShape = new Shape();

objFigure = new Circle();
objShape.CreateFigure(objFigure);

objFigure = new Rectalge();
objShape.CreateFigure(objFigure);
}

No comments:

Followers

Link