I have a couple of classes that want to pass each other some information and be called back later, using that information (Callback pattern).
Within my application, this mechanism serves two purposes:
- scheduled / delayed execution
- asynchronous execution involving messaging
My objects basically say to each other "when you're finished doing X, call me back and tell me to do Y with Z (because I'll have forgotten about it by then)". Where X might just be waiting for the right time, but also communicating with a remote service or calling a local function.
Now, were there function pointers (or equivalent) in Java, I would implement some "Job" class containing one plus the arguments it needs. For example, in PHP this structure would have to store a class name, a function name and an array of arguments. In C, it would be a pointer to the function and I'd have to make the arguments the same number and type for all calls.
In Java, the usual approach is to have an interface that's implemented by all classes that want to be called back, like this:
public interface ICallable {
public void call_me(Object data);
}
Now this wouldn't work for me, because
- the objects to be called back might have a different set of methods to take the call
- the caller is not the one to decide what call should be made
Maybe my problem is that I'm trying to have a common data structure and calling procedure for the various callbacks, but in principle, it seems to make sense to me.
What's a good design pattern to approach this situation in Java?