Factory Design Pattern falls under the category of creational design pattern. It deals with the problem of creating objects without specifying the exact class of object that will be created. It is abstracting the process of object generation which is determined at run-time.
The behavior of a PizzaFactory class is to Bake a Pizza. So, the PizzaFactory class will create the object based on the choice provided by the customer of whether it is a Dominos Pizza or Pizza Hut.
interface IBake
{
void Pizza();
}
public class DominosPizza: IBake
{
public void Pizza()
{
Console.WriteLine("Dominos Pizza is Served!");
}
}
public class PizzaHut: IBake
{
public void Pizza()
{
Console.WriteLine("Pizza Hut is Served!");
}
}
//The type of object created is determined at run-time.
class PizzaFactory
{
public static IBake makePizza(int choice)
{
IBake objPizza = null;
switch (choice)
{
case 1:
objPizza = new DominosPizza();
break;
case 2:
objPizza = new PizzaHut();
break;
default:
objPizza = new DominosPizza();
break;
}
return objPizza;
}
}
Now suppose your Client is a Console Application in this case. The code will be as below:
class Program
{
static void Main(string[] args)
{
IBake objPizza = null;
Console.WriteLine("Enter your choice of Pizza!");
int choice = Convert.ToInt32(Console.ReadLine());
objPizza = PizzaFactory.makePizza(choice);
objPizza.Pizza();
}
}