We use Factory design pattern when the object needs to be extended to sub classes. Simply return the object using the factory class.
We are working with an interface here.
Simple Factory
public interface IVehicleChoice
{
string Buy();
}
This implements IVehicleChoice
public class Car : IVehicleChoice
{
public string Buy()
{
return "Buying Car";
}
}
This implements IVehicleChoice
public class Bike : IVehicleChoice
{
public string Buy()
{
return "Buying Bike";
}
}
It doesn't implement IVehicleChoice. It has a choice mehod which return IVehicleChoice.
public class VehicleFactory
{
public static IVehicleChoice Choice(string choice)
{
IVehicleChoice myChoice = null;
if (!string.IsNullOrWhiteSpace(choice))
{
if (choice.ToLower() == "car")
{
myChoice = new Car();
}
else if (choice.ToLower() == "bike")
{
myChoice = new Bike();
}
}
return myChoice;
}
}
static void Main(string[] args)
{
//car
Console.WriteLine(VehicleFactory.Choice("car").Buy());
//bike
Console.WriteLine(VehicleFactory.Choice("bike").Buy());
Console.ReadLine();
}
We are working with an interface here.
Simple Factory
- Abstracts the creation details of the product
- Refers to the newly created object through an interface
- Any new type creation is handed with a chage of code in the factory class and not at the client code
Interface IVehicleChoice
public interface IVehicleChoice
{
string Buy();
}
Class Car
This implements IVehicleChoice
public class Car : IVehicleChoice
{
public string Buy()
{
return "Buying Car";
}
}
Class Bike
This implements IVehicleChoice
public class Bike : IVehicleChoice
{
public string Buy()
{
return "Buying Bike";
}
}
Factory Class
It doesn't implement IVehicleChoice. It has a choice mehod which return IVehicleChoice.
public class VehicleFactory
{
public static IVehicleChoice Choice(string choice)
{
IVehicleChoice myChoice = null;
if (!string.IsNullOrWhiteSpace(choice))
{
if (choice.ToLower() == "car")
{
myChoice = new Car();
}
else if (choice.ToLower() == "bike")
{
myChoice = new Bike();
}
}
return myChoice;
}
}
Call
static void Main(string[] args)
{
//car
Console.WriteLine(VehicleFactory.Choice("car").Buy());
//bike
Console.WriteLine(VehicleFactory.Choice("bike").Buy());
Console.ReadLine();
}