A detailed Java callback mechanism _java

Source: Internet
Author: User

There is always a certain interface between modules, which can be divided into three categories: synchronous invocation, callback, and asynchronous invocation. The following focuses on the callback mechanism.

1. Overview

The callback mechanism in Java is a more common mechanism, but it may be less used in your program, and the callback mechanism can be seen everywhere in some large frameworks. This article through some concrete examples, slowly approached the Java callback mechanism.

2. Callback

Callback: is called a method C in class B in Class A, and then in Class B it calls the method D,d in Class A, which is called the callback method. In practice, there will be different callback forms, such as the following.

2.1 Synchronous Callback

Here I suppose a situation like this.

A company's director B and his subordinates (project manager C) said to do a research, but do not have to C own pro. You can ask manager C to arrange the following programmer D to do it. Manager C found programmer D and told him to complete a research task now. And tell manager C about the results of the research. If there is a problem, continue. Because here's C let D do one thing, then D still have to communicate the result with C. This is the model of the callback. The following is a class diagram of a general callback:

First we need to have a callback interface Callbackinterface

Callbackinterface.java

Public interface Callbackinterface {public
  boolean check (int result);
}

In the background, programmer D is to communicate the results with Project manager C, so the project manager here needs to implement the above callback interface:

Manager.java

public class Manager implements Callbackinterface {

  private programmer programmer = NULL;

  Public Manager (programmer _programmer) {
    this.programmer = _programmer;
  }

  /**
   * For Boss issued the principal/public
  void entrust () {
    arrange ();
  }

  Arrange subordinates for study work
  private void Arrange () {
    System.out.println ("Manager is working on programmer");
    Programmer.study (manager.this);
    System.out.println ("The job is done for programmer, the Manager does the other thing." ");
  }

  @Override Public
  boolean check (int result) {
    if (result = = 5) {return
      true;
    }
    return false;
  }

}

For programmer D, he needs to hold a reference to manager C in order to communicate with him. However, this is the task that Director B lets manager C to arrange. That is to say, there are other managers, like manager B1, B2 and so on. Because the manager implements the callback interface, it's OK to let programmer D hold the interface directly. As follows:

Programmer.java

public class Programmer {public

  void study (Callbackinterface callback) {
    int = 0;
    do {
      result++;
      System.out.println ("The first" + result + "Results of the secondary study");
    } while (the!callback.check (result));

    System.out.println ("End of Research task");
  }


It's a little more straightforward for the director, because it's equivalent to a Client test:

Boss.java

public class Boss {public

  static void Main (string[] args) {
    Manager manager = new Manager (new Programmer ()); 
   manager.entrust ();
  }

Run Result:

Manager is arranging work for programmer
Results of the 1th study
Results of the 2nd study
Results of the 3rd study
Results of the 4th study
Results of the 5th study
End of research mission
The work for programmer has been done and the Manager has done other things.

2.2 Asynchronous callback

Or the above example, your project manager will not be waiting for your research results. Instead of giving the task to you, he doesn't care, he does it, you do it. Therefore, the function of the callback needs to be processed asynchronously.
So, here we need to modify the code for the programmer class as follows:

Programmer.java

public class Programmer {public

  programmer () {
  } public

  void study (Callbackinterface callback) {
    new Studythread (callback). Start ();

  ---------------------------Programmer is doing work---------------------------

  class Studythread extends Thread {

    Callbackinterface callback = null;

    Public Studythread (Callbackinterface _callback) {
      callback = _callback;
    }

    @Override public
    Void Run () {
      int = 0;
      do {
        result++;
        System.out.println ("The first" + result + "Results of the secondary study");
      } while (the!callback.check (result));

      System.out.println ("End of Research task");}}


Run Result:

Manager is arranging work for programmer
The work for programmer has been done and the Manager has done other things.
Results of the 1th study
Results of the 2nd study
Results of the 3rd study
Results of the 4th study
Results of the 5th study
End of research mission

2.3 Closures and callbacks

A closure (closure) is a callable object that records information from the scope in which it was created.

2.3.1 Normal Call

First, we can look at how the call is going to work under normal circumstances.
Incrementable.java

Interface Incrementable {
  void increment ();
}

This is an ordinary interface (in the ordinary call is just a normal interface, in the callback is the callback interface, this should be very well understood).

Callee1.java

Class Callee1 implements incrementable {

  private int i = 0;

  @Override public
  void Increment () {
    i++;
    System.out.println (i);
  }

}

Callbacks.java

public class Callbacks {public
  static void Main (string[] args) {
    Callee1 callee1 = new Callee1 ();
    Callee1.increment ();
  }

Callbacks is a test client class, there is nothing to say, look directly at the code above.

2.3.2 Callback Preliminary

There's nothing to say about the normal call, because it's something that a normal Java programmer should be able to handle without thinking about it.

Now if a callback is to be made, it is not possible for the structure or logic of the program to have only one callee (the object CALLEE1 by the callback), and a caller object is needed. The caller can write as follows:

Caller.java

Class Caller {

  private incrementable callbackreference;

  Public Caller (incrementable _callbackreference) {
    callbackreference = _callbackreference;
  }

  void Go () {
    callbackreference.increment ();
  }
}

Here Caller holds a reference to a callback interface Callbackreference, as the programmer in the above needs to hold a reference to a project manager so that it can be communicated to the project manager through this reference. The callbackreference here also played a role.

Now let's take a look at the writing of the Test class:

Callbacks.java

public class Callbacks {public
  static void Main (string[] args) {
    Callee1 callee1 = new Callee1 ();    
    Caller caller1 = new Caller (callee1);
    Caller1.go ();
  }

For the program code so far, it is entirely possible to compare the above project manager to arrange the programmer to investigate the technical difficulties of the code. Have the same thing.

2.3.3 Closure Callback

In contrast to normal callbacks, the core of a closure callback is naturally the closure, which is the control of the scope.
Now assume that a user (other programmer) has customized a Myincrement class and includes a increment method. As follows:

Class Myincrement {public

  void increment () {
    System.out.println ("mycrement.increment");
  }

  static void F (Myincrement increment) {
    increment.increment ();
  }
}

Another class Callee2 inherits from the above class:

Class Callee2 extends Myincrement {

  private int i = 0;

  public void Increment () {
    super.increment ();
    i++;
    System.out.println (i);
  }
}

Obviously if you want to call the increment () method here, it becomes a generic function call. So here we need to modify the above Callee2 class, the goal of which is to make the Callee2 class compatible with the Myincrement class increment () method and Incrementable () method. After modification:

Class Callee2 extends Myincrement {

  private int i = 0;

  public void Increment () {
    super.increment ();
    i++;
    System.out.println (i);
  }

  Private class Closure implements Incrementable {

    @Override public
    void Increment () {
      Callee2.this.increment ();
    }

  Incrementable getcallbackreference () {return
    new Closure ();
  }
}

Note that the Closure class here is a private class, which is an element of closure. Since the Closure class is private, it is necessary to have an open interface for manipulating Closure objects, and here is the Getcallbackreference () method above. The Caller class does not change.
For the test client, look directly at the code:

public class Callbacks {public
  static void Main (string[] args) {    
    Callee2 callee2 = new Callee2 ();
    Caller caller2 = new Caller (Callee2.getcallbackreference ());
    Caller2.go ();
  }

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.