理解Java当中的回调机制

发表于:2014-9-17 10:09  作者:JohnTsai   来源:51Testing软件测试网采编

字体: | 上一篇 | 下一篇 |我要投稿 | 推荐标签:

  在我们的例子中系统定时器支持回调方法:
1 // This is the SystemTimer implemented by your Operating System (OS)
2 // You don't know how this timer was implemented. This example just
3 // show to you how it could looks like. How you could implement a
4 // callback by yourself if you want to.
5 class SystemTimer {
6
7     List<TimeUpdaterCallBack> callbacks = new ArrayList<TimeUpdaterCallBack>();
8
9     public void registerCallBackForUpdatesEveryHour(TimeUpdaterCallBack timerCallBack) {
10         callbacks.add(timerCallBack);
11     }
12
13     // ... This SystemTimer may have more logic here we don't know ...
14
15     // At some point of the implementaion of this SystemTimer (you don't know)
16     // this method will be called and every registered timerCallBack
17     // will be called. Every registered timerCallBack may have a totally
18     // different implementation of the method updateTime() and my be
19     // used in different ways by different clients.
20     public void oneHourHasBeenExprired() {
21
22         for (TimeUpdaterCallBack timerCallBack : callbacks) {
23             timerCallBack.updateTime(System.currentTimeMillis());
24         }
25     }
26 }
  最后是我们虚拟简单的例子中的网站时间更新器:
1 // This is our client. It will be used in our WebSite example. It shall update
2 // the website's time every hour.
3 class WebSiteTimeUpdater {
4
5     public static void main(String[] args) {
6         SystemTimer SystemTimer = new SystemTimer();
7         TimeUpdaterCallBack webSiteCallBackUpdater = new WebSiteTimeUpdaterCallBack();
8         SystemTimer.registerCallBackForUpdatesEveryHour(webSiteCallBackUpdater);
9     }
10 }

【福利】填问卷 送2019精选测试大礼包+接口测试实战课程!
22/2<12

评 论

论坛新帖

顶部 底部


建议使用IE 6.0以上浏览器,800×600以上分辨率,法律顾问:上海瀛东律师事务所 张楠律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2019, 沪ICP备05003035号
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪公网安备 31010102002173号

51Testing官方微信

51Testing官方微博

扫一扫 测试知识全知道