回调函数的应用在于确保串行运算时,同时支持并行的处理。该模式在底层开发模式中应用非常广泛。
package com;
/**
* java回调应用
* @author zh.h
*
*/
public class TestCallBack {
public void getIntelRomet(CallBack callBack,String name) throws Exception{
Thread.sleep(3000);
callBack.solve(name);
}
public static void main(String[] args) {
TestCallBack testCallBack=new TestCallBack();
Other other = new Other(testCallBack);
try {
other.otherPlay("main");
} catch (Exception e) {
e.printStackTrace();
}
}
}
interface CallBack{
public void solve(String result);
}
class Other implements CallBack{
public Other(){
}
public Other(TestCallBack testCallBack){
this.testCallBack=testCallBack;
}
private TestCallBack testCallBack;
public void otherPlay(final String name) throws Exception{
/**
* 同步回调
*/
testCallBack.getIntelRomet(Other.this, name);
/**
* 异步回调
*/
new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("异步回调");
testCallBack.getIntelRomet(Other.this, name);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
//此处可以定义新的方法进行内部横向扩展。
doSomeThing();
}
public void doSomeThing(){
System.out.println("Other 横向内部扩展");
}
@Override
public void solve(String name) {
System.out.println("Other 对于接口CallBack 方法的实现==>name:"+name);
}
}