Reflection in Factory good practice?

I wanted to write a factory that creates a specific class and returns its interface to the client. Thus, I can separate the client from the direct dependence on a particular class. But at the same time, I do not want the factory to be dependent on a particular class. I can use Reflection to satisfy my need, but before doing this, I want to know if this is good practice.

+4
source share
3 answers

It's hard to say without much detail, but I usually expected that the factory implementation would depend on the particular class that instantiated it. In my opinion, this is a completely natural addiction.

If you want to make it a very general factory, which essentially adds value precisely because it uses reflection - essentially doing a small part of what most IoC containers do - then that's fine; but if it is a factory for one specific type, I would just accept the dependency. This is likely to lead to code that is easier to understand and verify, and will also be more efficient.

+10
source

Yes, your approach will be good practice. But there is already a framework that does this work for you. See MEF Scheme.

0
source

Yes, your approach is good, and I do not see any problems with it. But instead of wasting time on this, you should use some existing framework.

You can consider the Spring Framework IOC module .

0
source

Source: https://habr.com/ru/post/1438352/


All Articles