【发布时间】:2013-07-19 11:43:01
【问题描述】:
我一直在努力思考回调,并且一直在努力掌握这个概念。下面的代码是我找到的一个例子here
从头到尾我理解流程是这样的:
-
CallMe被实例化,从而调用了该类的构造函数 - 变量
en被设置,随后实例化EventNotifier类并调用它的构造函数,该构造函数被传递给对象CallMe的引用 - 变量
ie被设置为对象CallMe,该对象被传递到构造函数中 - 变量
somethinghappened设置为false(我假设将使用一些条件语句来确定是否设置其他值) - 嗯……完成了吗?
我不明白这段代码。 doWork 是如何被调用的?这如何表示一个事件?为什么不简单地从callme 的构造函数调用interestingevent .... 就此而言,为什么不直接调用dowork 来代替任何会改变somethinghappened 值的东西?
尽我所能,我似乎无法理解这个想法。我知道回调主要用于表示事件已发生,例如鼠标或按钮单击,但它如何在事件发生与被调用方法之间建立联系?不应该有一个循环来检查更改,从而触发事件吗?
有人可以提供一个(不过分简化的)java 回调的解释,并帮助澄清这样的事情有什么用处吗?
public interface InterestingEvent
{
public void interestingEvent ();
}
public class EventNotifier
{
private InterestingEvent ie;
private boolean somethingHappened;
public EventNotifier (InterestingEvent event)
{
ie = event;
somethingHappened = false;
}
public void doWork ()
{
if (somethingHappened)
{
ie.interestingEvent ();
}
}
}
public class CallMe implements InterestingEvent
{
private EventNotifier en;
public CallMe ()
{
en = new EventNotifier (this);
}
public void interestingEvent ()
{
// Wow! Something really interesting must have occurred!
// Do something...
}
}
编辑:请查看已批准答案中的 cmets... ---this--- 链接对我很有帮助 =)
【问题讨论】: