Search

Factory method pattern

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.

/*Factory Pattern*/

//interfce
public interface IPeople
{
string GetName();
}

public class Villagers : IPeople
{
public string GetName()
{
return "Village Guy";
}
}

public class CityPeople : IPeople
{
public string GetName()
{
return "City Guy";
}
}

public enum PeopleType
{
RURAL,
URBAN
}

///
/// Implementation of Factory - Used to create objects
///

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 the creation of one interface called IPeople and implemented two classes from it as Villagers and CityPeople. Based on the type passed into the factory object, We are sending back the original concrete object as the Interface IPeople.


A Factory method is just an addition to Factory class. It creates the object of the class through interfaces but on the other hand, it also lets the subclass to decide which class to be instantiated.


public interface IProduct
{
string GetName();
string SetPrice(double price);
}

public class IPhone : IProduct
{
private double _price;
public string GetName()
{
return "Apple TouchPad";
}

public string SetPrice(double price)
{
this._price = price;
return "success";
}
}

/* Almost same as Factory, just an additional exposure to do something with the created method */

public abstract class ProductAbstractFactory
{
protected abstract IProduct DoSomething();
public IProduct GetObject() // Implementation of Factory Method.
{
return this.DoSomething();
}
}

public class IPhoneConcreteFactory : ProductAbstractFactory
{
protected override IProduct DoSomething()
{
IProduct product = new IPhone();
//Do something with the object after you get the object.
product.SetPrice(20.30);
return product;
}
}