Factory Pattern creates Object of a class .
This is called creational Pattern because it creates the Object of a class
we no need create objects of classes during the design time like
clsEmployee objEmployee=new Employee();
in this text box you have to enter inputs like (CAR,BUS,VAN)
Please have a look on the below code My aim is i have a Text box on a web Page.
in this Text box user Enter the Vehicle Name
then it should display the price of the Vehicle
1. I created 3 classes (CAR,BUS,VAN)
2. I Created IVehicle Interface for making the uniformity class so we should implement GetPrice() method in all classes
3. I created a class called as Factory
4. In this Factory Class I have a method celled as CreateObject();
5. This method Creates objects of the class
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
Factory objFactory=new Factory() ;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
var obj = objFactory.CreateObject("WebApplication1."+TextBox1.Text.ToUpper());
Response.Write(obj.GetPrice());
}
}
class CAR : IVehicle
{
public int GetPrice()
{
return 300000;
}
}
class BUS : IVehicle
{
public int GetPrice()
{
return 600000;
}
}
class VAN : IVehicle
{
public int GetPrice()
{
return 5000000;
}
}
public interface IVehicle
{
int GetPrice();
}
class Factory
{
public IVehicle CreateObject(string ClassName)
{
IVehicle objIreport = null;
Type objectType = Type.GetType(ClassName);
if (objectType.IsClass)
{
objIreport =(IVehicle) Activator.CreateInstance(objectType);
}
return objIreport;
}
}
}