Hello folks. I’m experimenting with Java and just want to test something out. I came across a pretty interesting concept that I have not yet found a working solution for.
If you need some explanations: All of the middle class implements the interface with the method calc() which returns a value but we wont get into that. Method getValue() will try to invoke all of the calc() methods from the classes (the external class is a thought of an add-on), and get combine their return values into int value.
An idea I have is using some reflection to look up the class name, but I thought that maybe inefficient. Using HashMaps to register the classes, but I have no idea how to pull the classes out from the set and invoke a method from them. Just some thoughts.
I haven’t got into advance Java programming yet, but this is an interesting concept I would like to solve. Thank you for reading.
Your description sounds like you could use the observer pattern for this. Using reflection just to call a method on a list of known object is a bit of an overkill, I’d say.
I didn’t understand the goal you want to achieve here yet, but maybe you want to have a look at the visitor pattern as well. If you plan to add more methods like the mentioned calc() it could be worth to split the algorithm from the classes.
Both patterns are documented very good and pretty common in Java applications. Maybe if you tell a little bit more about your goal I can provide more input.
Are you not trying to write an event bus? I quickly threw this together some time ago.
(I honestly have no idea if this is good written, it can be that some day I find another way to do this. Without the reflection)