回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用来调用其所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现方直接调用,而是在特定的事件或条件发生时由另外的一方调用的,用于对该事件或条件进行响应。
下面两个实例
c++代码
//回调函数测试用例 #include "stdafx.h" #include<stdio.h> /*serer 端程序*/ int (*g_pFun)(int x, int y); //执行函数,内部调用回调函数 int plat() { int r; int a = 10; int b =15; r = g_pFun(a,b);//回调函数 printf("%d\n", r); return 0; } /*client端实现代码*/ //注册函数 int RegFun(int (*pFun)(int x, int y)) { g_pFun = pFun; return 0; } int Max(int x, int y) { return x > y ? x : y; } int Min(int x, int y) { return x > y ? y : x; } int main(void) { RegFun(Max);//注册函数Max plat();//执行函数 RegFun(Min);//注册函数Min plat(); return 0; }
java代码package test; import caller.caller; import MyCallInterface.MyCallInterface; public class mytest implements MyCallInterface{ public void method() { System.out.println("回调"); } public static void main(String args[]) { caller call = new caller(); call.setCallfuc(new mytest()); call.call(); } } package MyCallInterface; public interface MyCallInterface { public void method(); } package caller; import MyCallInterface.MyCallInterface; public class caller { public MyCallInterface mc; public void setCallfuc(MyCallInterface mc) { this.mc = mc; } public void call() { this.mc.method(); } }