1. 什么是回调函数 回调函数(callback Function),顾名思义,用于回调的函数。 回调函数只是一个功能片段,由用户按照回调函数调用约定来实现的一个函数。回调函数是一个工作流的一部分,由工作流来决定函数的调用(回调)时机。回调函数包含下面几个特性: 1、属于工作流的一个部分; 2、必须按照工作流指定的调用约定来申明(定义); 3、他的调用时机由工作流决定,回调函数的实现者不能直接调用回调函数来实现工作流的功能;
2. 回调机制
回调机制是一种常见的设计模型,他把工作流内的某个功能,按照约定的接口暴露给外部使用者,为外部使用者提供数据,或要求外部使用者提供数据。
3、使用场景
(1)在必须给别的函数提供接口的时候</p>
(2)在需要定时操作,或者条件操作的时候
4、回调方法测试用例:
(1)多线程的Runnable就属于一个回调接口,也就是别的类定义规则,你实现传入,由别人调用你的方法罢了 。
-
package com.gy.appsdk.dao;
-
-
-
-
-
-
-
interface WindowListener{
-
public void open();
-
-
}
-
-
-
public class Window {
-
-
private WindowListener windowListener;
-
-
public void registerWindowListener(WindowListener windowListener){
-
this.windowListener = windowListener;
-
}
-
-
public void show(){
-
if(windowListener!=null){
-
windowListener.open();
-
}
-
}
-
}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
(2)熟悉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");
-
-
-
ren.regist(a);
-
ren.regist(b);
-
-
-
ren.doWork();
-
}
-
}
|