What is factory method?
Rajanikant Hawaldar
Select an image from your device to upload
Factory is a Creational design pattern. Which is used to create different object on condition basis. You can make a method whose return type is an interface/base class and it take a parameter and on the basis of that the method will return object of any class which is implementing that interface. Example:-
public interface IJunkFood { string Prepare(); } public class Burger : IJunkFood { public string Prepare() { return "Burger is Ready"; } } public class Pizza : IJunkFood { public string Prepare() { return "Pizza is Ready"; } } public class OtherFood : IJunkFood { public string Prepare() { return "Other Junk Food is Ready"; } } public IJunkFood GetJunkFood(string type) { if (type == "Burger") return new Burger(); if (type == "Pizza") return new Pizza(); else return new OtherFood(); } String pizza = GetJunkFood("Pizza").Prepare(); String burger = GetJunkFood("Burger").Prepare();
public interface IJunkFood {
string Prepare();
}
public class Burger : IJunkFood
{
public string Prepare()
return "Burger is Ready";
public class Pizza : IJunkFood
return "Pizza is Ready";
public class OtherFood : IJunkFood
return "Other Junk Food is Ready";
public IJunkFood GetJunkFood(string type) {
if (type == "Burger")
return new Burger();
if (type == "Pizza")
return new Pizza();
else
return new OtherFood();
String pizza = GetJunkFood("Pizza").Prepare();
String burger = GetJunkFood("Burger").Prepare();