Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Factory pattern deals with the instantiation of object without exposing the instantiation logic. In other words, a Factory is actually a creator of object which has common interface.
http://3.bp.blogspot.com/_DSP5FXX4Isw/S_RaN0qt2BI/AAAAAAAAC9w/v_cy_PNyapI/s320/factory.JPG
//Empty vocabulary of Actual object
public interface IPeople
{
string GetName();
}
public class Villagers : IPeople
{
#region IPeople Members
public string GetName()
{
return "Village Guy";
}
#endregion
}
public class CityPeople : IPeople
{
#region IPeople Members
public string GetName()
{
return "City Guy";
}
#endregion
}
public enum PeopleType
{
RURAL,
URBAN
}
/// <summary>
/// Implementation of Factory - Used to create objects
/// </summary>
public class Factory
{
public IPeople GetPeople(PeopleType type)
{
IPeople people = null;
switch (type)
{
case PeopleType.RURAL :
people = new Villagers();
break;
case PeopleType.URBAN:
people = new CityPeople();
break;
default:
break;
}
return people;
}
}
In the above code you can see I have created one interface called IPeople and implemented two classes from it as Villagers and CityPeople. Based on the type passed into the factory object, I am sending back the original concrete object as the Interface IPeople.