回调的定义:
软件模块之间总是存在着一定的接口,从调用方式上,可以把他们分为三类:同步调用、回调和异步调用。同步调用是一种阻塞式调用,调用方要等待对方执行完毕才返回,它是一种单向调用;回调是一种双向调用模式,也就是说,被调用方在接口被调用时也会调用对方的接口(有待商榷);异步调用是一种类似消息或事件的机制,不过它的调用方向刚好相反,接口的服务在收到某种讯息或发生某种事件时,会主动通知客户方(即调用客户方的接口)。回调和异步调用的关系非常紧密,通常我们使用回调来实现异步消息的注册,通过异步调用来实现消息的通知。
一般在 API 中使用回调。
回调允许调用者主动调用客户程序的代码。
它的触发机制类似抛出事件。
举个例子:当你要系统枚举系统中的所有窗口,使用回调后,系统每找到一个窗口就把控制权交给你,由你的回调程序处理这个窗口,这样大大简化了程序。
再比如:一个端口监听程序,如果使用回调,当有数据时,才需要运行主程序的代码。而不用回调,则主程序每隔一定时间都要去判断是否有数据到达,程序不但复杂,而且浪费资源。
回调程序在API的地位相当于DOS的中断处理程序。
回调程序的实质是提供一个参数作为回调函数的入口地址。由调用的函数根据地址反过来调用客户程序。
|
public interface InterestingEvent
{
// This is just a regular method so it can return something or
// take arguments if you like.
public void interestingEvent ();
}
|
|
public class EventNotifier
{
private InterestingEvent ie;
private boolean somethingHappened;
public EventNotifier (InterestingEvent event)
{
// Save the event object for later use.
ie = event;
// Nothing to report yet.
somethingHappened = false;
}
public void doWork ()
{
// Check the predicate, which is set elsewhere.
if (somethingHappened)
{
ie.interestingEvent ();
}
//...
}
// ...
}
|
|
public class CallMe implements InterestingEvent
{
private EventNotifier en;
public CallMe ()
{
// Create the event notifier and pass ourself to it.
en = new EventNotifier (this);
}
// Define the actual handler for the event.
public void interestingEvent ()
{
// Wow!Something really interesting must have occurred!
// Do something...
}
//...
}
|
本文详细解释了回调机制的概念及其在软件开发中的应用。介绍了同步调用、回调和异步调用的区别,并通过Java语言实例展示了如何利用接口实现回调,提高程序效率。
3万+

被折叠的 条评论
为什么被折叠?



