首页 > 编程语言 > 详细

java回调机制

时间:2016-02-29 12:45:29      阅读:144      评论:0      收藏:0      [点我收藏+]
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();       
    }
}

 

java回调机制

原文:http://www.cnblogs.com/zhengtu2015/p/5226784.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!