Saturday, March 27, 2010

C# implementation of Builder pattern

The builder pattern Separates the construction of a complex object from its representation.

The players in this pattern are:
1. Product (Room)
Represents the complex object which includes many classes(parts)
2. Builder (RoomBuilder)
Specifies an abstract class or an interface for creating parts of a Product object
3. ConcreteBuilder (WoodBuilder, GlassBuilder)
  • Constructs parts of the product by implementing the Builder class/interface
  • provides a way for retrieving the product
4. Director (House)
Constructs an object (room) using the Builder class/interface

So, you use the Builder pattern when:

  • the object to be constructed has many parts and might have different representations.
  • you need control over the construction process.



//The library code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BuilderPattern
{
// The 'Product' class
public class Room
{
string _type;
List _parts = new List<string>();
public Room(string type)
{
_type = type;
}
public void Add(string part)
{
_parts.Add(part);
}
public void Show()
{
Console.WriteLine("\nProduct Parts:");
foreach (string part in _parts)
Console.Write(part+"\t");
Console.WriteLine();
}
}

// The 'Builder' abstract class
public abstract class RoomBuilder
{
protected Room room;
public Room Room
{
get { return room; }
}
public abstract void BuildDoor();
public abstract void BuildWindow();
}

// The 'ConcreteBuilder 1' class
public class WoodBuilder : RoomBuilder
{
public WoodBuilder()
{
room = new Room("WoodRoom");
}
public override void BuildDoor()
{
room.Add("Wood-Door");
}
public override void BuildWindow()
{
room.Add("Wood-Window");
}
}

// The 'ConcreteBuilder 2' class
public class GlassBuilder : RoomBuilder
{
public GlassBuilder()
{
room = new Room("GlassRoom");
}
public override void BuildDoor()
{
room.Add("Glass-Door");
}
public override void BuildWindow()
{
room.Add("Glass-Window");
}
}

// The 'Director' class
public class House
{
public void Construct(RoomBuilder roomBuilder) // you may label it as 'static'
{
roomBuilder.BuildDoor();
roomBuilder.BuildWindow();
roomBuilder.BuildWindow();
/* You can provide Additional Director
* with another series of steps
* like adding tow doors..*/
}
}
}


3 comments:

Unknown said...

\\The client code
using BuilderPattern;

namespace BuilderClient
{
class MainProgram
{
static void Main(string[] args)
{
// Create one director and two builders
House myHouse = new House();
RoomBuilder WBuilder=new WoodBuilder();
RoomBuilder GBuilder=new GlassBuilder();
// Construct two products
myHouse.Construct(WBuilder);
Room R1 = WBuilder.Room;
R1.Show();

myHouse.Construct(GBuilder);
Room R2 = GBuilder.Room;
R2.Show();
Console.Read();
}
}
}

Unknown said...

\\The out put
Product Parts:
Wood-Door Wood-Window Wood-Window

Product Parts:
Glass-Door Glass-Window Glass-Window

Kumait Muhammad said...

very nice man, keep this good stuff