当前位置: 移动技术网 > IT编程>开发语言>Java > java 实现回调代码实例

java 实现回调代码实例

2019年07月22日  | 移动技术网IT编程  | 我要评论

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<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回调机制的介绍,有需要的同学可以参考下。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网