码迷,mamicode.com
首页 > 编程语言 > 详细

java回调机制

时间:2016-02-29 12:46:54      阅读:151      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!