The policy design pattern and the function pointers in the C language

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.