Factory Method
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.
http://1.bp.blogspot.com/_DSP5FXX4Isw/S_RbTPlViOI/AAAAAAAAC90/5k2WeV6P2aE/s320/factorymethod.JPG
public interface IProduct
{
string GetName();
string SetPrice(double price);
}
public class IPhone : IProduct
{
private double _price;
#region IProduct Members
public string GetName()
{
return "Apple TouchPad";
}
public string SetPrice(double price)
{
this._price = price;
return "success";
}
#endregion
}
/* Almost same as Factory, just an additional exposure to do something with the created method */
public abstract class ProductAbstractFactory
{
public IProduct DoSomething()
{
IProduct product = this.GetObject();
//Do something with the object after you get the object.
product.SetPrice(20.30);
return product;
}
public abstract IProduct GetObject();
}
public class ProductConcreteFactory : ProductAbstractFactory
{
public override IProduct GetObject() // Implementation of Factory Method.
{
return this.DoSomething();
}
}
You can see I have used GetObject in concreteFactory. As a result, you can easily call DoSomething() from it to get the IProduct.
You might also write your custom logic after getting the object in the concrete Factory Method. The GetObject is made abstract in the Factory interface.