java回调机制

1. 定义一个接口InterestingEvent ,回调方法nterestingEvent(String event) 简单接收一个String 参数。

interface InterestingEvent {
    public void interestingEvent(String event);
}

 
2. 实现InterestingEvent接口,事件处理类

class CallMe implements InterestingEvent {
    private String name;
    public CallMe(String name){
        this.name = name;
    }   
    public void interestingEvent(String event) {
        System.out.println(name + ":[" +event  + "] happened");
    }
}

 
3. 事件管理者,或事件通知者

class EventNotifier {
    private List<CallMe> callMes = new ArrayList<CallMe>();
   
    public void regist(CallMe callMe){
        callMes.add(callMe);
    }
   
    public void doWork(){
        for(CallMe callMe: callMes) {
            callMe.interestingEvent("sample event");
        }
    }   
}

 
4. 测试

public class CallMeTest {
    public static void main(String[] args) {
        EventNotifier ren = new EventNotifier();
        CallMe a = new CallMe("CallMe A");
        CallMe b = new CallMe("CallMe B");

        // regiest
        ren.regist(a);
        ren.regist(b);
       
        // test
        ren.doWork();       
    }
}
原文地址:https://www.cnblogs.com/zhengtu2015/p/5226784.html