Java Delegates
source: http://www.cutthecrap.biz/software/delegates.html
Delegates are a useful construct in event-based systems. Essentially Delegates are objects that encode a method dispatch on a specified object. This document shows how java inner classes provide a more generic solution to such problems.
What is a Delegate?
Really it is very similar to a pointer to member function as used in C++. But a delegate contains the target object alongwith the method to be invoked. Ideally it would be nice to be able to say:
obj.registerHandler(ano.methodOne);
..and that the method methodOne
would be called on ano
when some specific event was received.
This is what the Delegate
structure achieves.
Java Inner Classes
It has been argued that Java provides this functionality via inner classes and thus does not need the additional Delegate construct.
obj.registerHandler(new Handler() { public void handleIt(Event ev) { methodOne(ev); } } );
At first glance this seems correct but at the same time a nuisance. Because for many event processing examples the simplicity of the Delegates
syntax is very attractive.
General Handler
However, if event-based programming is used in a more pervasive manner, say, for example, as a part of a general asynchronous programming environment, there is more at stake.
In such a general situation, it is not sufficient to include only the target method and target object instance. In general there may be other parameters required, that are determined within the context when the event handler is registered.
In this more general situation, the java approach can provide a very elegant solution, particularly when combined with use of final
variables:
void processState(final T1 p1, final T2 dispatch) { final int a1 = someCalculation(); m_obj.registerHandler(new Handler() { public void handleIt(Event ev) { dispatch.methodOne(a1, ev, p1); } } ); }
final * final * final
Got your attention?
Note that the final
variables are accessible from within the anonymous class method definitions. Be sure to study this code carefully to understand the ramifications. This is potentially a very powerful technique. For example, it can be used to good effect when registering handlers in MiniDOM and in more general situations.
By contrast, the Delegate
construct does not provide a solution for this more general requirement, and as such should be rejected as an idiom on which designs can be based.