何爲回調函數,關鍵二字在於回調,意思就是可以方便的回去調用某個函數。
在C++ 下,就是 函數指針的 具體運用,通過函數指針來標記將來調用的函數,實現回調
#include <stdio.h>
void printWelcome(int len)
{
printf("歡迎歡迎 -- %d/n", len);
}
void printGoodbye(int len)
{
printf("送客送客 -- %d/n", len);
}
void callback(int times, void (* print)(int))
{
int i;
for (i = 0; i < times; ++i)
{
print(i);
}
printf("/n我不知道你是迎客還是送客!/n/n");
}
void main(void)
{
callback(10, printWelcome);
callback(10, printGoodbye);
printWelcome(5);
}
*******************************************************************************
在Java下,回調函數 就是 接口 的具體運用。
個人理解的JAVA回調函數的幾個基本條件:
1. 回調函數可以定義爲藉口類中的函數 (必須被繼承類重定義)
2.主叫類繼承回調函數借口,並且定義回調函數的內容,(一般是通知主叫類,之前調用的工作已經完成了)
3. 主叫類擁有一個被叫類的成員對象,用於 異步回調(長時間操作) 或者 同步回調 (段時間操作)的具體執行類成員
4. 被叫類需要註冊主叫類,一般在被調用前構造的時候註冊主叫類對象引用,用於在調用完成後及時通知主叫類(調用主叫類的回調函數)
例如 A 想要 B 替他做點事情,因此A就打電話給B 說,你幫我做件事情吧,我還有事情要忙,B說沒問題我做完了就回你電話(A知道B做完了)。
這裏面 主調人和回調函數的執行者都是A, 但是明明是A 叫B幫他做的事情, 但是B要在完成的時候告訴A我做完了,因此需要知道A的電話號碼。
interface CallBack
{
void notifyOK ();
};
class Caller implements CallBack
{
public void askForSth ()
{
/*
* unsynchronized call
*/
new Thread (new runnable() // A call B to do this thing.
{
B.askedForSth();
}).start()
playOtherActivity();<span style="white-space:pre"> </span>// A is busy with other things, not wait for B result
}
private playOtherActivity()
{
/*
* Do other things
*/
system.out.println("A is playing other activity ... ");
}
@override
void notifyOK ()
{
system.out.println("B has finished !");
}
};
class Callee
{
Callee (Caller caller)
{
this.A = caller; // register caller
}
private Caller A;
public static void askedForSth()
{
*/
* askedforsth, long time process
*/
system.out.println("B is busy handling ...");
if ( NULL != A)
{
A.notifyOK();<span style="white-space:pre"> </span>// B is done, notify A. use registed caller A
}
}
};
public class Solution {
public static void main(String[] args)
{
Caller a ;
Callee b(a);
a.askForSth();
}