Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does it make more sense to use the factory pattern rather than an overloaded constructor to instantiate an object?

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?

like image 880
JaredCacurak Avatar asked Oct 09 '09 00:10

JaredCacurak


2 Answers

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.

like image 186
James Black Avatar answered Jan 04 '23 17:01

James Black


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.

like image 44
TrueWill Avatar answered Jan 04 '23 17:01

TrueWill