In Karl Seguin's Foundations of Programming there is a small section on using the factory pattern. He closes the passage by stating "you can accomplish the same functionality with constructor overloading", but doesn't indicate when or why?
So,when does it make more sense to use the factory pattern rather than an overloaded constructor to instantiate an object?
If you want to have looser coupling then the factory makes more sense, as you can then just call the car factory, pass in the suv enum, and the correct class is returned. Your application doesn't care which class was actually returned, as long as it meets your needs.
If you're doing Dependency Injection but need to create instances of the dependency as needed within the dependant, one option is to inject an interface to a class factory. The factory can return an interface or an abstract class. This provides flexibility, testability, and decoupling at the cost of some complexity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With