Object initialization by references without access to a constructor other than the standard
Suppose I have an interface called "Controller". Several classes implement this interface and I am not aware of these classes (for example, the class names are in the xml file). Now, in order for these classes that implement the controller to work, they need to get some references to other objects (data objects, perhaps). And this is my question, namely, what is the best way to initialize such objects (controllers)?
I've thought of several solutions, but I'm not entirely sure what is the best approach here.
First , when creating an object from a class name, I could look for a "special" constructor (via reflection) that has references to the objects that the Controller needs. But from what I've read in other questions, this is less likely a good solution because I would force the custom constructor to exist in the class. And sometimes I read that reflection in general is evil and best avoided.
Second . I am adding a special init (a, b, c) interface to the Controller interface that needs to be called immediately after the object is created. This will lead to a sequence of calls (first init (..), then rest) to the object to make it work, which is also bad. Btw, are init () methods usually perform poorly in interfaces?
Third : after reading this comment, I thought about the following: instead of having the class name of the class that implements the Controller interface (in the xml file) I have a factory class name that belongs to a specific Controller class. And this factory will implement the interface with createController (a, b, c) method and factory, then it needs to know what class it should create and also what constructor should cause other references to wrap (such as these objects). The downside to this would be an extra class to instantiate the Controller class and maybe a little bit of overhead.
What do you think is the best way to do this? Or can you think of something else that could be better than these three ways?
Thanks!
a source to share
From the approaches you mentioned, I would choose the second one (factory). However, since what you are doing is a form of dependency injection, also consider Guice, http://code.google.com/p/google-guice/ - this may allow you to automate most of this work.
a source to share