A發送消息給B,B處理好A要求的事情後,將結果返回給A,A再對B返回的結果來做進一步的處理。
A、 回調的實現
/**
* 回調接口
* @author KOOK
*
*/
public interface CallBack {
/**
* 執行回調方法
* @param objects 將處理後的結果作爲參數返回給回調方法
*/
public void execute(Object... objects );
}
Java是面向對象的語言,因此回調函數就變成了回調接口。
B、 消息的發送者
/**
* 簡單本地發送異步消息的類
* @author KOOK
*
*/
public class Local implements CallBack,Runnable{
/**
* 遠程接收消息的類,模擬point-to-point
*/
private Remote remote;
/**
* 發送出去的消息
*/
private String message;
public Local(Remote remote, String message) {
super();
this.remote = remote;
this.message = message;
}
/**
* 發送消息
*/
public void sendMessage()
{
/**當前線程的名稱**/
System.out.println(Thread.currentThread().getName());
/**創建一個新的線程發送消息**/
Thread thread = new Thread(this);
thread.start();
/**當前線程繼續執行**/
System.out.println("Message has been sent by Local~!");
}
/**
* 發送消息後的回調函數
*/
public void execute(Object... objects ) {
/**打印返回的消息**/
System.out.println(objects[0]);
/**打印發送消息的線程名稱**/
System.out.println(Thread.currentThread().getName());
/**中斷髮送消息的線程**/
Thread.interrupted();
}
public static void main(String[] args)
{
Local local = new Local(new Remote(),"Hello");
local.sendMessage();
}
public void run() {
remote.executeMessage(message, this);
}
}
C、 遠程消息的接收者
/**
* 處理消息的遠程類
* @author KOOK
*
*/
public class Remote {
/**
* 處理消息
* @param msg 接收的消息
* @param callBack 回調函數處理類
*/
public void executeMessage(String msg,CallBack callBack)
{
/**模擬遠程類正在處理其他事情,可能需要花費許多時間**/
for(int i=0;i<1000000000;i++)
{
}
/**處理完其他事情,現在來處理消息**/
System.out.println(msg);
System.out.println("I hava executed the message by Local");
/**執行回調**/
callBack.execute(new String[]{"Nice to meet you~!"});
}
}
執行Local類的main方法。
注意Local類中紅色背景的那行:
remote.executeMessage(message, this);
executeMessage方法需要接收一個message參數,表示發送出去的消息,而CallBack參數是他自己,也就是這裏的this。表示發送消息後,由Local類自己來處理,調用自身的execute方法來處理消息結果。
如果這裏不是用this,而是用其他的CallBack接口的實現類的話,那就不能稱之爲“回調”了,在OO的世界裏,那就屬於“委派”。也就是說,“回調”必須是消息的發送者來處理消息結果,否則不能稱之爲回調。這個概念必須明確。