What is factory method?
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();
A Factory method will provide an encapsulation ( centralization) for the various objects creation for your project. This will save scattering of the objects creation logic all over the application. The design patterns helps in a much cleaner code along with giving Single responsibilities to the business classes (which now do not have to worry about the added responisbility of object creation.) Please keep in mind that in order for a Factory creation to work better , it further needs to be injected using the DI Principle. Thanks