回调
案例: 妈妈和儿子告别,儿子到了学校就通知妈妈
写法一:
/**
* 回调接口
*/
public interface CallListener {
void call();
}
public class Son {
/**
* 模拟儿子骑车上学花费5s
*
* @param listener
*/
public void ride(CallListener listener) {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
listener.call();
}
}
public class Mother {
private Son son;
public Mother(Son son) {
this.son = son;
}
public void sayBye() {
System.out.println("回调开始");
son.ride(new CallListener() {
@Override
public void call() {
System.out.println("我到学校了");
}
});
System.out.println("回调结束");
}
}
写法二
public class Son {
private CallListener listener;
public void registerListener(CallListener listener) {
this.listener = listener;
}
public void ride() {
//3.
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
//4.
listener.call();
}
}
public class Mother {
private Son son;
public Mother(Son son) {
this.son = son;
}
public void sayBye() {
//1
son.registerListener(new CallListener() {
@Override
public void call() {
//5.
System.out.println("我到学校了");
}
});
//2.
son.ride();
}
}