舉個例子來說,假設當一個事件發生的時候,我們想它被通知,那么我們定義一個接口: 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編譯器的工作。