在C语言中,有一个非常重要的概念—函数指针,其最重要的功能是实现回调函数。
什么是回调函数?
所谓回调函数,就是指函数先在某处注册,而它将在稍后某个需要的时候被调用。在Window系统中,开发人员想让系统动态链接库(Dynamic Link Library,DLL)调用自己编写的一个方法,于是利用DLL当中回调函数的接口来编写程序,通过传递一个函数的指针来调用,这个过程就称为回调。
回调函数一般用于截获消息、获取系统信息或处理异步事件。
函数指针一般作为函数的参数来使用,开发人员在使用时可以根据自己的需求传递自定义的函数来实现指定的功能,例如,在实现排序算法时,可以通过传递一个函数指针来决定两个数的先后顺序,从而最终决定该算法时升序还是降序排序。
在Java语言中没有指针的概念,那么如何才能在Java语言中实现类似于函数指针的功能呢?
可以使用接口与类来实现同样的效果。具体而言,应先定义一个接口,然后在接口中声明要调用的方法,接着实现这个接口,最后把这个实现类的一个对象作为参数传递给调用程序,调用程序通过这个参数来调用指定的函数,从而实现回调函数的功能。示例如下:
/*
* 接口定义一个用来比较大小的方法
* */
interface IntCompare{
public int cmp(int a,int b);
}
class Cmp1 implements IntCompare{
public int cmp(int a,int b){
if (a>b)
return 1;
else if (a<b)
return -1;
else
return 0;
}
}
class Cmp2 implements IntCompare{
public int cmp(int a,int b){
if (a>b)
return -1;
else if (a<b)
return 1;
else
return 0;
}
}
public class CallbackDemo {
public static void insertSort(int[] a,IntCompare cmp){
if(a!=null){
for (int i=1;i<a.length;i++){
int temp=a[i],j=i;
if(cmp.cmp(a[j-1],temp)==1){
while (j>=1&&cmp.cmp(a[j-1],temp)==1){
a[j]=a[j-1];
j--;
}
}
a[j]=temp;
}
}
}
public static void main(String[] args) {
int[] array1={7,3,19,40,4,7,1};
insertSort(array1,new Cmp1());
System.out.print("升序排序:");
for (int i:array1){
System.out.print(i+" ");
}
System.out.println();
int[] array2={7,3,19,40,4,7,1};
insertSort(array2,new Cmp2());
System.out.print("降序排序:");
for (int i:array2){
System.out.print(i+" ");
}
}
}
程序运行结果为:
升序排序:1 3 4 7 7 19 40
降序排序:40 19 7 7 4 3 1
上例定义了一个用来比较大小的接口IntCompare,这个接口实际上充当了C语言中函数指针的功能,在使用时,开发人员可以根据实际需求传入自定义的类。在上例中分别有两个类Cmp1和Cmp2都实现了这个接口,分别用来实现升序排序和降序排序时的使用。其实这也是策略设计模式所用到的思想。