Why would you want a callback? The normal parameter passing mechanism lets caller provide the callee with information, but provides only meager flow of information in the reverse direction, the single returned result primitive or Object. Further the callee cannot provide further information back to the caller once it has returned. The callback mechanism allows a two-way flow of information and exchange of computing resources between caller and callee.
Consider a component consisting of a panel of buttons. The caller wants to control the labellings on the buttons, how they are rendered etc. The callee wants to notify the caller whenever one of the buttons was pressed, and which one. The callback mechanism, sometimes called a Listener mechanism, allows the callee to notify the caller, the listener, of interesting events, or to use some of the methods the caller has access to.
There are four basic techniques to fake a callback function in Java.
- Subclassing. Subclass the calling class with an overridden callback method. Pass "this " as a parameter.
- Delegation via subclassing. Pass a subclassed Callback delegate object that knows how to invoke the callback method(s).
- Pass a Callback delegate object that implements an interface for the callback method(s).HeapSort: source code for an example of the delegate technique
This is how it is most commonly done. It offers most flexibility, - Use inner classes to define an anonymous callback class, instantiate an anonymous callback delegate object, and pass it
as a parameter all in one line. This technique with EventListeners tends to muddle GUI and
program logic making your GUI code non-reusable. Unless the anonymous inner classes are simple, it is generally wiser to
make them ordinary free-standing named classes.
If you don’t already understand delegates, that probably sounds like Greek. Just look at the HeapSort example. Once you understand that code, you will easily understand the other three variants. It is much simpler than it first sounds.
Callback has a totaly different meaning in the context of security. For secure login you call the server. It then calls you back. This makes it harder for you to spoof being someone else. This may be done over phone lines or over the Internet. It is the same scheme a jealous husband might use to ensure his wife is really home as she claims.
http://mindprod.com/jgloss/callback.html
No comments:
Post a Comment