Factory pattern is one of Creational Pattern of Gang of Four Design patterns in .Net. In this pattern, an interface or abstract class is used for creating an object but let sub class decide which class to instantiate.

Factory method pattern can be broadly categorized in four steps:

  1. Product
  2. Concrete Product
  3. Creator
  4. Concrete Creator

  1. Product: In this phase we create an interface or abstract class for creating the objects in its child classes.
  2. Concrete Product: In this phase we implement the Product defined in above phase
  3. Creator: This is generally a abstract class which has factory method which returns the object of type product.
  4. Concrete Creator: In this phase we implement the creator class and override the factory method and return an instance of Concrete product.

Below is the implementation of Factory pattern with C# example:

//Creation of Product
pubic interface IVehicle
{
void Wheels(int NoOfWheels)
}
//Creation of Concrete Product
public class Car:IVehicle
{
public void Wheels(int NoOfWheels)
{
Console.WriteLine("It is Car with "+ NoOfWheels.ToString()+" wheels");
}
}
//Creation of Concrete Product 2
public class Byke:IVehicle
{
public void Wheels(int NoOfWheels)
{
Console.WriteLine("It is Byke with "+ NoOfWheels.ToString()+" wheels");
}
}
//Creation of Creator i.e., with Factory Method
public abstract class VehicleFactory
{
public abstract IVehicle GetWheels(string VehicleType);
}
//Creation of Concrete Creator

public class ConcVehicleFactory: VehicleFactory
{

public override IVehicle GetWheels(string VehicleType)
{
Switch(VehicleType)
{
Case "Car":
return new Car();

Case "Byke":
return new Byke();

default:
return null;
}
}
}
//Using Factory Pattern in Main function
class Program
{

public static void Main(string[] args)
{
VehicleFactory vf=new ConcVehicleFactory();

IVehicle car= vf.GetWheels("Car");
car.Wheels(4);

IVehicle byke= vf.GetWheels("Byke");
byke.GetWheels(2);

Console.ReadLine();
}
}