Java callback JAVA实现回调 .

来源:互联网 发布:cdrx4官方软件下载 编辑:程序博客网 时间:2024/06/05 16:44

======================================================
注:本文源代码点此下载
======================================================

java实现回调

熟悉ms-windows和x windows事件驱动设计模式的开发人员,通常是把一个方法的指针传递给事件源,当某一事件发生时来调用这个方法(也称为“回调”)。java的面向对象的模型目前不支持方法指针,似乎不能使用这种方便的机制。

java支持interface,通过interface可以实现相同的回调。其诀窍就在于定义一个简单的interface,申明一个被希望回调的方法。

例如,假定当某一事件发生时会得到通知,我们可以定义一个interface:

public interface interestingevent {

// 这只是一个普通的方法,可以接收参数、也可以返回值

public void interestingevent();

}

这样我们就有了任何一个实现了这个接口类对象的手柄grip。

当一事件发生时,需要通知实现interestingevent 接口的对象,并调用interestingevent() 方法。

class eventnotifier {

private interestingevent ie;

private boolean somethinghappened;

public eventnotifier(interestingevent event) {

ie = event;

somethinghappened = false;

}

public void dowork() {

if (somethinghappened) {

// 事件发生时,通过调用接口的这个方法来通知

ie.interestingevent();

}

}

}

在这个例子中,用somethinghappened 来标志事件是否发生。

希望接收事件通知的类必须要实现interestingevent 接口,而且要把自己的引用传递给事件的通知者。

public class callme implements interestingevent {

private eventnotifier en;

public callme() {

// 新建一个事件通知者对象,并把自己传递给它

en = new eventnotifier(this);

}

// 实现事件发生时,实际处理事件的方法

public void interestingevent() {

// 这个事件发生了,进行处理

}

}

以上是通过一个非常简单的例子来说明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 callmes = new arraylist();

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();

}

}


======================================================
在最后,我邀请大家参加新浪APP,就是新浪免费送大家的一个空间,支持PHP+MySql,免费二级域名,免费域名绑定 这个是我邀请的地址,您通过这个链接注册即为我的好友,并获赠云豆500个,价值5元哦!短网址是http://t.cn/SXOiLh我创建的小站每天访客已经达到2000+了,每天挂广告赚50+元哦,呵呵,饭钱不愁了,\(^o^)/
原创粉丝点击