java回调机制

所谓回调:就是A类中调用B类中的某个方法C,然后B类中反过来调用A类中的方法D,D这个方法就叫回调方法,这样子说你是不是有点晕晕的,其实我刚开始也是这样不理解,来看看人家说的比较经典的回调方式:
Class A实现接口CallBack callback——背景1
class A中包含一个class B的引用b ——背景2
class B有一个参数为callback的方法f(CallBack callback) ——背景3
A的对象a调用B的方法 f(CallBack callback) ——A类调用B类的某个方法 C
然后b就可以在f(CallBack callback)方法中调用A的方法 ——B类调用A类的某个方法D

举个例子说明一下:小明做作业遇到一个问题,“1+1=?”。小明不会,于是去厨房问妈妈。妈妈说她现在比较忙,没时间答复小明,等她做完家务会去帮他结题。小明说,那自己先去做其他题目。
下面用代码来说明一下:

//首先定义一个回调接口,对应于背景1
public interface CallBack {
public void result(String result);
}

//定义小明类,小明需要有一个回调方法,让妈妈在算好题目之后来通知自己,所以需要实现回调接口,对应于背景2
public class XiaoMing implements CallBack {
private Mother mother;

public XiaoMing(Mother mother) {
this.mother = mother;
}

public void askQuestion(final String question) {
System.out.println("小明:妈妈,请问" + question);
new Thread(new Runnable() {
@Override
public void run() {
mother.executeQuestion(XiaoMing.this, question);
}
}).start();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
doOtherHomework();
}

public void doOtherHomework() {
System.out.println("小明:那我先去做其他题目。");
}

@Override
public void result(String result) {
System.out.println("妈妈:" + result);
}
}

//定义妈妈类,在这里妈妈需要在做完家务之后,去告诉小明答案,即调用小明的方法,对应于背景3
public class Mother {
public void executeQuestion(CallBack callback, String question) {
System.out.println("妈妈:等我做完家务再帮你结题。");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("妈妈:我做完家务了,现在就来解答你的问题。");
callback.result("1+1=2。");
}
}
//测试类
public class test {
public static void main(String[] args) {
Mother mother = new Mother();

XiaoMing son = new XiaoMing(mother);

son.askQuestion("1+1=几?");
}
}

猜你喜欢

转载自cc414011733.iteye.com/blog/2287609