您的位置:首页 > 编程语言 > C语言/C++

C++ JAVA下回调函数机制和原理比较分析

2015-11-04 16:21 896 查看
何为回调函数,关键二字在于回调,意思就是可以方便的回去调用某个函数。

在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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: