举个例子来说,假设当一个事件发生的时候,我们想它被通知,那么我们定义一个接口: 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) { // Signal the even by invoking the interface's method. ie.interestingEvent (); } //... } // ... }
在这个例子中,我们使用了somethingHappened这个标志来跟踪是否事件应该被激发。在许多事例中,被调用的方法能够激发interestingEvent()方法才是正确的。 希望收到事件通知的代码必须实现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... } //... }
希望这点小技巧能给你带来方便。
关于作者: John D. Mitchell在过去的九年内一直做顾问,曾经在Geoworks使用OO汇编语言开发了PDA软件,爱好于写编译器,Tcl/Tk和Java系统。和人合著了《Making Sense of Java》,目前从事Java编译器的工作。