“Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.”
A factory pattern is one that returns an instance of one of several possible classes depending on the data provided to it. Usually all of the classes it returns should have a common base class and common methods, but implementations of the methods may be different.
Create an Interface
public interface IVehicle
{
Int32 GetWheelCount();
}
Create Classes
public class Auto :IVehicle
{
public Int32 GetWheelCount()
{
return 4;
}
}
public class MotorCycle :IVehicle
{
public Int32 GetWheelCount()
{
return 4;
}
}
public class FactoryPattern
{
public IVehicle GetInstance(Int32 Id)
{
IVehicle iVehicle=null;
if (Id == 1)
{
iVehicle = new Auto();
}
else
{
iVehicle = new MotorCycle();
}
return iVehicle;
}
}
Create an aspx page ,add the below in the page load
void Page_Load(object sender, EventArgs e)
{
FactoryPattern _factoryPattern = new FactoryPattern();
IVehicle iVehicleAuto = _factoryPattern.GetInstance(1);
IVehicle iVehicleMotorCycle = _factoryPattern.GetInstance(2);
Response.Write("
Auto has " + iVehicleAuto.GetWheelCount() + " Wheels");
Auto has " + iVehicleAuto.GetWheelCount() + " Wheels");
Response.Write("
MotorCycle has " + iVehicleMotorCycle.GetWheelCount() + " Wheels");
MotorCycle has " + iVehicleMotorCycle.GetWheelCount() + " Wheels");
}