I wanted to write a factory which instantiates a concrete class and return its interface to the client. In this way I can decouple the client from having dependancy on the concrete class directly. But, at the same time I don’t want factory to have dependancy on the concrete class. I can use Reflection to satisfy my need but before doing so I want to know whether this is a good practice.
Share
It’s hard to say without more specifics, but I’d usually expect a factory implementation to have a dependency on the concrete class it’s creating instances of. It’s a perfectly natural dependency, in my view.
If you want to make it a very general factory which essentially adds value precisely because it uses reflection – in essence doing a small part of what most IoC containers do – then that’s fine; but if it’s a factory for one specific type, then I’d just take the dependency. It’s likely to lead to code which is simpler to understand and test, as well as rather more efficient.