There is a very important concept in C language-function pointers, the most important function is to implement a callback function (the function is registered somewhere, and it will be called at a later time) in the Java language does not have the concept of pointers, but can use the interface and pointers to achieve similar functions, in particular, Should first define an interface, and finally pass an object of the implementation class as a parameter to the calling program, the caller invokes the specified function through this parameter to implement the callback function (where the interface is like a registered place, the implementation class is "registrant", when the implementation class as a formal parameter, when needed)
PackageStraterydemo;Importjava.util.Arrays;//This also has a similar example in the Think in JavaInterfaceintcompare{ Public intcmpintAintb);}classCmp1Implementsintcompare{@Override Public intcmpintAintb) {if(A >b) {return1; } Else if(A <b) {return-1; } return0; }}classCmp2Implementsintcompare{@Override Public intcmpintAintb) {if(A >b) {return-1; } Else if(A <b) {return1; } return0; }} Public classstraterytest{ Public Static voidInsertsort (int[] A, intcompare CMP) { if(A! =NULL) { for(inti = 1; i < a.length; i++) { inttemp = 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 voidMain (string[] args) {int[] arr1 = {2, 4, 56, 72, 1, 54, 68798 }; Insertsort (arr1,NewCMP1 ()); System.out.println (arrays.tostring (arr1)); int[] arr2 = {223, 42, 56, 72, 1, 54, 68798 }; Insertsort (ARR2,NewCMP2 ()); System.out.println (arrays.tostring (ARR2)); }}
The policy design pattern and the function pointers in the C language