Rajanikant Hawaldar
What is factory method?

What is factory method?

  • Sonil  Kumar
    Jul, 2021 26

    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:-

    1. public interface IJunkFood {
    2. string Prepare();
    3. }
    4. public class Burger : IJunkFood
    5. {
    6. public string Prepare()
    7. {
    8. return "Burger is Ready";
    9. }
    10. }
    11. public class Pizza : IJunkFood
    12. {
    13. public string Prepare()
    14. {
    15. return "Pizza is Ready";
    16. }
    17. }
    18. public class OtherFood : IJunkFood
    19. {
    20. public string Prepare()
    21. {
    22. return "Other Junk Food is Ready";
    23. }
    24. }
    25. public IJunkFood GetJunkFood(string type) {
    26. if (type == "Burger")
    27. return new Burger();
    28. if (type == "Pizza")
    29. return new Pizza();
    30. else
    31. return new OtherFood();
    32. }
    33. String pizza = GetJunkFood("Pizza").Prepare();
    34. String burger = GetJunkFood("Burger").Prepare();

    • 2
  • Manish Pandey
    Mar, 2022 6

    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

    • 1


Most Popular Job Functions


MOST LIKED QUESTIONS