下面给出上述例子的完整实现:

/*
 * 考虑这样一个应用:希望在某个事件发生时得到通知
 */
interface InterestingEvent {
    
    public void interestingEvent();
    
}
 
 
class EventNotifier {
    
    private InterestingEvent ie;        //写成private List<InterestingEvent> eventList可以监听多个事件
    private boolean somethingHappened;
    
    public EventNotifier(InterestingEvent ie) {
        this.ie = ie;
        this.somethingHappened = false;
    }
    
    public void setHappened() {
        this.somethingHappened = true;
    }
    
    public void doWork() {
        if (somethingHappened) {
            ie.interestingEvent();
        }
    }
    
}
 
 
class ButtonPressedEvent implements InterestingEvent {
 
    @SuppressWarnings("unused")
    private EventNotifier en;
    
    public ButtonPressedEvent() {
        en = new EventNotifier(this);
    }
    
    public void interestingEvent() {
        System.out.println("button pressed ");
    }
    
}
 
 
class EventNotifierTest {
    
    public static void test() {
        //这里有两种调用方法。其中第二种采用匿名内部类,其原理跟上面“改变Client名字”是一样的
        EventNotifier en = new EventNotifier(new ButtonPressedEvent());
        en.setHappened();
        en.doWork();
        
        EventNotifier en2 = new EventNotifier(new InterestingEvent(){
            public void interestingEvent() {
                System.out.println("inputtext change ");
            }
        });
        en2.setHappened();
        en2.doWork();
        
    }
}
 
 
//这个类是用来测试的
public class JavaInterfaceCallBack {
    
    public static void main(String[] args) {
       
        ChangeNameTest.test();
        EventNotifierTest.test();
        
    }
 
}