Java callback function understanding and application __java

Source: Internet
Author: User
Java callback function understanding and application

Callback: is called a method C in class B in Class A, and then in Class B, in turn, calls the method in Class A d,d this method is called the callback method, so that you are not a little dizzy.
Before I understood it, I was a face, and when I understood it, I found that the callback function principle of javascript is basically the same, one is to pass the object as a parameter, one is to pass the function as a parameter.
Excerpt from Wikipedia to define:
In computer programming, a callback function, or callback, is a reference to a piece of executable code passed through a function parameter to another code. This design allows the underlying code to invoke a subroutine defined at the top level.

For example, there is a programmer and a project manager, the XX project manager arranges the task for the programmer to complete, the programmer obtains the task and notes is the XX Project manager arranges the task, the programmer completes the task, obtains informs the XX project manager the way, sends a message to inform the project manager the task has completed.

The following example:
Create a new project manager class:

public class Projectmanager {

    private String name;

    Public Projectmanager (String name)
    {
         this.name =name;
    }

    Public String getName ()
    {return
        this.name;
    }

    /**
     * Notification method
     * @param msg
     *
    /public void Noticeme (String msg)
    {
        System.err.println (msg);
    }

    /**
     * Schedule Tasks
     * @param task */public
    void Arrange (String Task)
    {
        //schedule programmer to work
        new Programmer (). Receivetask (Task, this);
    }

    public void Dootherwork ()
    {
        System.err.println ("project manager doing other things ...");
    }


Create a new programmer class:

Import Java.util.concurrent.TimeUnit;


The public class Programmer {

    //is noted as the XX project manager, not the other project manager
    Projectmanager Manager;
    /** Programmer accepts task
    /public void Receivetask (String Task,projectmanager Manager)
    {
        This.manager = Manager;
        try {
            //The programmer begins to perform the task
            this.excutetask (Task);
        } catch (Interruptedexception e) {
            e.printstacktrace ();
        }
    /** perform task *
    /private void Excutetask (String task) throws Interruptedexception
    {
        SYSTEM.ERR.PRINTLN ("Executive project manager:" +manager.getname () + "scheduled task-->" +task);
        TimeUnit.SECONDS.sleep in Mission implementation
        (1);
        Task Complete
        this.finished (tasks);
    }
    /** task complete/public
    void finished (String task)
    {
        //Get the method to notify the project manager and issue a notification
        //function callback, this is not a real callback
        . Manager.noticeme (Manager.getname () + "Hello, the task you have arranged" +task+ "has been completed. ");
    }

}

New Test class:

public class Callbacktest {

    /**
     * @param args
     *
    /public static void main (string[] args) {
        Projectmanager prjmgr = new Projectmanager ("Wang Xiang");
        Prjmgr.arrange ("Complete database design tonight ...");
        Prjmgr.dootherwork ();
    }

Run Result:

In practice, however, the project manager may have many contacts, some of which may be ineffective. Then how can I know which is the actual notification method? That requires the project manager to specify which way is correct, so that the programmer can just remember the contact method. In C + +, to use the callback function, the lost function needs to tell the caller its own pointer address, but there is no pointer in Java, what to do. We can implement the definition of callback functions through an interface (interface).
Define a notification interface:

Public interface Notice {public
    void Noticeme (String msg);

Overwrite project manager class:

public class Projectmanager implements notice{

private String name;

Public Projectmanager (String name)
{
 this.name =name;
}

Public String getName ()
{return
this.name;
}

/**
 * Notification method
 * @param msg
 *
/@Override public
void Noticeme (String msg)
{
SYSTEM.ERR.PRINTLN (msg);

/**
 * Schedule Tasks
 * @param task */public
void Arrange (String Task)
{
//schedule programmer to work
new Programmer (). Receivetask (Task, this);
}

public void Dootherwork ()
{
System.err.println ("project manager doing other things ...");
}

Rewriting programmer classes

Import Java.util.concurrent.TimeUnit;


public class programmer{

    //Specifies the mode of notification
    Notice Notice;
    /** Programmer accepts task *
    /public void Receivetask (String task,notice Notice)
    {
        this.notice = Notice;
        try {
            //programmer begins to perform task
            this.excutetask (tasks);
        } catch (Interruptedexception e) {
            e.printstacktrace ();
        }
    }
    /** perform task/
    private void Excutetask (String task) throws Interruptedexception
    {
        System.err.println (" Execute project manager: Scheduled Task--> "+task";
        TimeUnit.SECONDS.sleep in Mission implementation
        (1);
        Task Complete
        this.finished (tasks);
    }
    /** task complete/public
    void finished (String task)
    {
        //Get the method to notify the project manager and issue
        a notification//callback notification
        Notice.noticeme ("Hello, the task you have arranged" +task+ "has been completed. ");
    }

}

So why do we use callback functions?
Simply put, I live too much, or have other things to do, I do not want to do, I assign this work to others to complete, and the results of the completion of the show I can do.

If you see this here, if you don't understand, so I'm going to put it another way: The callback function is when someone calls me, I tell someone that the address of my method is there, and then someone else will just find the address, no need to go to the system to apply for the memory address and find out where the method is.

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.