Java中实现类似C语言中函数指针的功能

为了开题漂亮一点,Gd引用了一大段书上的话。

首先来看一下什么是C语言中的指针,字面上理解就是一个类似实现定位功能的结构。指针最重要的功能,就是实现回调函数,所谓回调函数,就是指让函数先在某处注册,而它将在稍后某个需要的时候被调用。回调函数一般用于截获消息,获取系统信息或处理异步事件。

那么在Java中究竟如何实现回调函数呢?书就抄到这里,举个例子来说明,程序员A编写了一段程序a,其中预留有回调函数接口,并封装好了该程序。程序员B要让a调用自己程序b中的一个方法,于是,他通过a中的接口回调属于自己程序b中的方法。

上面说了这么多,大家应该也看见了辣个出现频繁的神秘关键字,没错!就是接口,下面通过一个实现排序功能的程序来说明如何通过接口来实现回调函数:

interface IntCompare{
	//定义IntCompare接口,其中定义cmp方法
	public int cmp(int a,int b);
}

class Cmp1 implements IntCompare{
	//创建普通类Cmp1实现接口IntCompare,重写cmp方法(为升序排序创造条件)
	@Override
	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{
	//创建普通类Cmp2实现接口IntCompare,重写cmp方法(为降序排序创造条件)
	@Override
	public int cmp(int a,int b)
	{
	if(a>b)
		return -1;
	else if(a<b)
		return 1;
	else
		return 0;
    }
}
public class Test {
	//定义方法实现升序排序和降序排序
	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 = {1,8,5,7,3,6,4};
		insertSort(array1,new Cmp1());
		System.out.print("升序排序:");	
		for(int i=0;i<array1.length;i++)
		{
			System.out.print(array1[i]);
		}
		System.out.println();
		int[] array2 = {1,8,5,7,3,6,4};
		insertSort(array2,new Cmp2());
		System.out.print("降序排序:");	
		for(int i=0;i<array2.length;i++)
		{
			System.out.print(array2[i]);
		}
	}
}

运行结果如下:

升序排序:1345678

降序排序:8765431

上述例子中通过接口将不同的排序方法整合到一起,调用不同的方法时只需要在排序方法中创建不同的实现接口的普通类的对象,从而实现函数回调。


猜你喜欢

转载自blog.csdn.net/qq_39209361/article/details/80846801