对于回调的理解

对于回调的理解

Java中没有指针的概念,如何实现类似于C语言中函数指针的功能?

一、回调定义

在C语言中,有一个非常重要的概念—指针,在Windows系统中,开发人员想让系统动态链接库(Dynamic Link Library,DLL)调用自己编写的一个方法,于是利用DLL当中回调函数的接口来编写程序,通过传递一个函数指针来被调用,这个过程称为回调。

1.1用途

截获消息、获取系统信息或处理异步事件。

举例:程序员小王写了一段代码a,预留有回调接口并封装了该程序。程序员小李要让a调自己的程序b中的一个方法,于是他通过a中的接口回调属于自己的程序b中的那个方法。

二、Java代码举例实现

定义一个接口,两个实现类分别实现该接口,但是实现的内部方法不同,最后进行排序调用两种方法,进行升序、降序排列。

整数比较接口
interface IntCompare {
    public int compare(int a, int b);
}

两个实现类

class Compare1 implements IntCompare {

    @Override
    public int compare(int a, int b) {
        if (a > b) {
            return 1;
        } else if (a < b) {
            return -1;
        } else {
            return 0;
        }
    }
}

class Compare2 implements IntCompare {

    @Override
    public int compare(int a, int b) {
        if (a > b) {
            return -1;
        } else if (a < b) {
            return 1;
        } else {
            return 0;
        }
    }
}
进行回调实现排序
public class CallBackSort {
	//插入排序
    public static void insertSort(int[] a, IntCompare cmp) {
        if (a != null) {
            for (int i = 1; i < a.length; i++) {
                int temp = a[i];
                int j = i;
                if (cmp.compare(a[j - 1], temp) == 1) {
                    while (j >= 1 && cmp.compare(a[j - 1], temp) == 1) {
                        a[j] = a[j - 1];
                        j--;
                    }
                }
                a[j] = temp;
            }
        }
    }


    public static void main(String[] args) {
        int[] arr1 = {7,3,19,40,4,7,1};
        insertSort(arr1,new Compare1());//实现类1
        System.out.println("升序排列: ");
        for (int i : arr1) {
            System.out.print(i + " ");
        }
        System.out.println();
        insertSort(arr1,new Compare2());//实现类2
        System.out.println("降序排列: ");
        for (int i : arr1) {
            System.out.print(i + " ");
        }

    }
}
结果
升序排列: 
1 3 4 7 7 19 40 
降序排列: 
40 19 7 7 4 3 1 

总结:

可以看出接口充当了C语言中指针的功能,回调的方式利用了继承多态的思想,个人认为与代理模式也非常相似。

相关资料:

  1. 百度百科
  2. Java程序员面试笔试

如有错误,敬请批评指正!

发布了3 篇原创文章 · 获赞 1 · 访问量 89

猜你喜欢

转载自blog.csdn.net/weixin_46053707/article/details/103796189