Actually why we need factory function in OOP and we can NEW to create a copy of the any object?
-
See the linked duplicate for a description of factory functions - it should help you. – Jack Bashford Jun 03 '19 at 02:28
1 Answers
So there are many reasons factory methods make sense:
Throwing Exceptions: If you need to do some work on creation that may throw an exception. Lets say you were creating an object based on a row in a table. You want the logic for populating the object to be with the object, since otherwise you have needless coupling. At the same time, constructors should generally not throw exceptions. So what happens if your constructor is asked to create an object based on a row that doesn't exist? Or what if there are issues accessing the database? Having a factory function allows you more latitude to handle this, from throwing an exception, to returning null, to returning a different kind.
Polymorphic construction: What if you want to construct an object based on user input? You could thread all of the user input needed to create the object through function calls until you get to the place you need to create the object. Or you could create a factory object that houses all of these parameters, and pass that through. The second way adds encapsulation, so if in the future you need to refine the input used, you can make it at the factory construction, and you're done. This also allows for multiple factories inheriting from a common interface, in case the created class needs to be different, or the creation algorithm differs somehow. This would be referred to as an abstract factory, and is a very common pattern in OOP.
All of this being said, I've definitely seen factory methods used where they aren't necessary, so factory methods are not a panacea. But they are an important tool that a good software architect will use often.

- 585
- 4
- 17