Creational Pattern - Builder Author
Date Of Submission
User Level
Ashish Jaiman
02/19/2002
Beginner
Example
C# Implementation
using System;
using System.Collections;
public interface IHouse
{
bool GetBackyard();
long NoOfRooms();
string Discription();
}
public class CApt:IHouse
{ private bool mblnBackyard;
private Hashtable Rooms;
public CApt()
{ CRoom room;
Rooms = new Hashtable();
room = new CRoom();
room.RoomName = "Master Bedroom";
Rooms.Add ("room1",room);
room = new CRoom();
room.RoomName = "Second Bedroom";
Rooms.Add ("room2",room);
room = new CRoom();
room.RoomName = "Living Room";
Rooms.Add ("room3",room);
mblnBackyard = false;
}
public bool GetBackyard()
{
return mblnBackyard;
}
public long NoOfRooms()
{
return Rooms.Count;
}
public string Discription()
{
IDictionaryEnumerator myEnumerator = Rooms.GetEnumerator();
string strDiscription;
strDiscription = "This is an Apartment with " + Rooms.Count + " Rooms \n";
strDiscription = strDiscription + "This Apartment doesn't have a backyard \n";
while (myEnumerator.MoveNext())
{
strDiscription = strDiscription + "\n" + myEnumerator.Key + "\t" + ((CRoom)myEnumerator.Value).RoomName;
}
return strDiscription;
}
}
public class CSFH:IHouse
{ private bool mblnBackyard;
private Hashtable Rooms;
public CSFH()
{
CRoom room;
Rooms = new Hashtable();
room = new CRoom();
room.RoomName = "Master Bedroom";
Rooms.Add ("room1",room);
room = new CRoom();
room.RoomName = "Second Bedroom";
Rooms.Add ("room2",room);
room = new CRoom();
room.RoomName = "Third Room";
Rooms.Add ("room3",room);
room = new CRoom();
room.RoomName = "Living Room";
Rooms.Add ("room4",room);
room = new CRoom();
room.RoomName = "Guest Room";
Rooms.Add ("room5",room);
mblnBackyard = true;
}
public bool GetBackyard()
{
return mblnBackyard;
}
public long NoOfRooms()
{
return Rooms.Count;
}
public string Discription()
{
IDictionaryEnumerator myEnumerator = Rooms.GetEnumerator();
string strDiscription;
strDiscription = "This is an Single Family Home with " + Rooms.Count + " Rooms \n";
strDiscription = strDiscription + "This house has a backyard \n";
while (myEnumerator.MoveNext())
{
strDiscription = strDiscription + "\n" + myEnumerator.Key + "\t" + ((CRoom)myEnumerator.Value).RoomName;
}
return strDiscription;
}
}
public interface IRoom
{
string RoomName{get;set;}
}
public class CRoom:IRoom
{
private string mstrRoomName;
public string RoomName
{
get
{
return mstrRoomName;
}
set
{
mstrRoomName = value;
}
}
}
public class CDirector
{
public IHouse BuildHouse(bool blnBackyard)
{
if (blnBackyard)
{
return new CSFH();
}
else
{
return new CApt();
}
}
}
public class Client
{
static void Main(string[] args)
{
CDirector objDirector = new CDirector();
IHouse objHouse;
objHouse = objDirector.BuildHouse(bool.Parse(args[0]));
Console.WriteLine(objHouse.Discription());
}
}