Lets look on a simple example: assume that I have three classes implemeting IPersonRepository
: SQLPersonRepository
, WebPersonRepository
, InMemoryPersonRepository
. I also have PersonRepositoryFactory
class which is simple Factory method pattern implementation - contains GetPersonRepository
methods which have enum/string as parameter. How could I create Factory pattern (or in other words centralize my object creation) when SQLPersonRepository
needs dependency for: SQLConnection
or string to database path, WebPersonRepository
needs some http settings object and InMemoryPersonRepository
has no dependencies? I could pass it in Factory constructor or as method parameter but it'd be ugly, unclean and unmaintable especially if I had more IPersonRepository
implementations.
1 Answer
I suggest to implement PersonRepositoryFactory
as an abstract factory, with subclasses SQLPersonRepositoryFactory
, WebPersonRepositoryFactory
and InMemoryPersonRepositoryFactory
. Those subclasses can have different constructor parameters (like SQLConnection
, HttpSetting
or no parameters). Once you have initialized those three factory objects, you can use them through an ordinary factory method for producing of many IPersonRepository
objects, all with the same SQL connection or http settings.