+ 3

Abstract Factory pattern | What is benefits with so many interfaces

Hi First thing first. Please find below codes samples created for Factory pattern and Abstract factory pattern. Correct me if any thing wrong is observed in these example codes. https://code.sololearn.com/cA2A10A124a1 https://code.sololearn.com/cA16a1a14A20 Now, question is about usefulness. what benefit we gets from abstract factory? In case of factory method , main function (i.e. client) does not know how object is created and it is the benefit that object creation is hidden from end user. Another benefit is that with addition of new flavor, client code i.e. main function need not to be changed. In contrast to this, abstract factory pattern creates required object in main function itself... So, both the advantage I mentioned for factory pattern is gone in this case....Another disadvantage is addition of virtual keyword which increases cost at run time. So, what is benefit of using abstract pattern?

7th Feb 2021, 8:49 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 Answers
+ 7
I also recommed the following website for beginners trying to wrap their heads around the motivations and benefits of many common design patterns. https://refactoring.guru/design-patterns/factory-method https://refactoring.guru/design-patterns/abstract-factory
9th Feb 2021, 7:12 AM
David Carroll
David Carroll - avatar
+ 4
Ketan Lalcheta I just implemented a code on Factory Method Pattern that might help you better understand. Hopefully, you can follow the C# code. https://code.sololearn.com/ctRGOOXlr8y3/?ref=app In short, the benefits have to do with extending and maintaining the code where refactoring the existing code is avoided. That said, your implementation of Factory Method Pattern is missing the key requirement where logic in the base factory class calls a method that is overridden in the factory sub classes. Your version is tightly coupled to it's factory subtypes which is a bad practice that should be avoided. A decoupled approach would defer the creation to the derived factories without knowing the sub type. This would eliminate having to modify the core / base class with new derived types, which would also satisfy the Open/Closed Principle (OCP), - the 2nd SOLID Principle. OCP is "Open for extension, closed for modification." Hopefully, this explanation makes sense. đŸ˜‰đŸ€ž
9th Feb 2021, 7:02 AM
David Carroll
David Carroll - avatar