Java callback mechanism of CallBack detail and example code

  • 2020-06-03 06:31:33
  • OfStack

Java callback mechanism

Summary:

With the recent study of java, you have been exposed to the callback mechanism (CallBack). I felt quite confused when I first met CallBack, and I searched for relevant explanations on the Internet, which were either passed over by words or simply defined CallBack. Of course, it's not a problem for me to read the explanations online after I understand the callback. However, as a beginner, I was missing a step by step process. Here, I will describe my personal understanding of the callback mechanism in order from shallow to deep. If there is anything wrong, please feel free to comment!

Before you begin, imagine a scenario in which a child in kindergarten has just learned to add up under 10.

Chapter 1. The origin of the story

Kindergarten teacher on the blackboard to write a formula "1 + 1 =", by xiaoming classmate to fill in the blanks.

Since he has learned addition within 10, Xiao Ming can calculate the problem by himself. The code to simulate the process is as follows:


public class Student
 {
  private String name = null;

  public Student(String name)
  {
   // TODO Auto-generated constructor stub
   this.name = name;
  }

  public void setName(String name)
  {
   this.name = name;
  }

  private int calcADD(int a, int b)
  {
   return a + b;
  }

  public void fillBlank(int a, int b)
  {
   int result = calcADD(a, b);
   System.out.println(name + " Mental arithmetic :" + a + " + " + b + " = " + result);
  }
 }

When xiao Ming was filling in the blanks (fillBalnk), he directly calculated (clacADD) 1 in his head and got the result 2, and wrote the result in the blank. The test code is as follows:


public class Test
 {
  public static void main(String[] args)
  {
  int a = 1;
   int b = 1;
   Student s = new Student(" Xiao Ming ");
   s.fillBlank(a, b);
  }
 }

The results are as follows:


 Xiao Ming mental arithmetic :1 + 1 = 2

This process is done entirely by the instance object of the Student class alone and does not involve a callback mechanism.

Chapter 2. The fault of the kindergarten teacher

Break, kindergarten teacher whim on the blackboard wrote "168 + 291 =" let Xiaoming finish, and then back to the office.

Flower brush! Why do all the teachers have a hard time with Xiao Ming? Clearly beyond the outline of the good! At this time, xiao Ming students obviously can no longer rely on mental arithmetic as above to complete, is meng forced when the class of small red students handed over 1 can only calculate the addition of the calculator (dishonest business)!! Xiao Ming happened to know how to use a calculator, so he got the result through the calculator and finished filling in the blanks.

The calculator code is:


public class Calculator
 {
  public int add(int a, int b)
  {
   return a + b;
  }
 }

Modify the Student class to add a method for using a calculator:


public class Student
 {
  private String name = null;

  public Student(String name)
  {
   // TODO Auto-generated constructor stub
   this.name = name;
  }

  public void setName(String name)
  {
   this.name = name;
  }

  @SuppressWarnings("unused")
  private int calcADD(int a, int b)
  {
   return a + b;
  }

  private int useCalculator(int a, int b)
  {
   return new Calculator().add(a, b);
  }

  public void fillBlank(int a, int b)
  {
   int result = useCalculator(a, b);
   System.out.println(name + " Use a calculator :" + a + " + " + b + " = " + result);
  }
 }

The test code is as follows:


public class Test
 {
  public static void main(String[] args)
  {
   int a = 168;
   int b = 291;
   Student s = new Student(" Xiao Ming ");
   s.fillBlank(a, b);
  }
 }

The results are as follows:


 Xiao Ming USES a calculator :168 + 291 = 459

There is still no callback mechanism involved in the process, but some of Ming's work has been transferred, assisted by the calculator.

The kindergarten teacher is back

Found that Xiao Ming completed the addition of three digits, the teacher think Xiao Ming is very smart, is a plastic talent. So he wrote "26549 + 16487 =" on the blackboard and asked Xiao Ming to fill in the blanks before class. Then he went back to the office.

Xiao Ming looked at the small friends outside the classroom, can not help but sad from it. Don't go out to play, this break will be useless!! Looking at the small red again 1 pass up the calculator, xiaoming xinsheng 1 meter: let the small red.

Xiao Ming told Xiao Hong that the topic was "26549 + 16487 =", then pointed out the specific location of the results, and then went out to play happily.

So instead of writing out little Red alone, let's just think of this calculator that can only add and little Red as a whole, a super calculator that can do the math and fill in the blanks. The parameters to be passed by this super calculator are two addend Numbers and the position to fill in the blank, and these contents need to be informed by Xiao Ming in advance, that is, Xiao Ming wants to leak his 1 part method to Xiao Hong. The simplest method is to tell Xiao Hong his reference and 1 block of two addend Numbers.

Therefore, the super calculator's add method should contain two operands and a reference to Ming himself, as follows:


public class SuperCalculator
 {
  public void add(int a, int b, Student xiaoming)
  {
   int result = a + b;
   xiaoming.fillBlank(a, b, result);
  }
 }

Now Xiaoming does not need to calculate in his head or use a calculator, so he only needs one way to ask Xiao Hong for help. The code is as follows:


public class Student
 {
  private String name = null;

  public Student(String name)
  {
   // TODO Auto-generated constructor stub
   this.name = name;
  }

  public void setName(String name)
  {
   this.name = name;
  }

  public void callHelp (int a, int b)
  {
   new SuperCalculator().add(a, b, this);
  }

  public void fillBlank(int a, int b, int result)
  {
   System.out.println(name + " Ask Xiao Hong for help :" + a + " + " + b + " = " + result);
  }
 }

The test code is as follows:


public class Test
 {
  public static void main(String[] args)
  {
   int a = 26549;
   int b = 16487;
   Student s = new Student(" Xiao Ming ");
   s.callHelp(a, b);
  }
 }

The operation result is:


public class Test
 {
  public static void main(String[] args)
  {
  int a = 1;
   int b = 1;
   Student s = new Student(" Xiao Ming ");
   s.fillBlank(a, b);
  }
 }
0

The execution process is as follows: Xiaoming calls the add method of Xiaoming (new SuperCalculator()) through its own callHelp method, and passes its reference (this) as parameter 1 during the call. After xiaoming gets the result with the calculator, she calls back Xiaoming's fillBlank method and fills the result in the blank space on the blackboard.

Light lamp light! At this point, the callback function is officially introduced. Ming's fillBlank method is often referred to as the callback function.

In this way, it is obvious that Xiao Ming does not need to wait until the addition is done and the result is filled on the blackboard to play with his friends when he completes the task of filling in the blanks. The task of filling in the blanks is done by super calculator Xiao Hong. The advantages of a pullback are beginning to show.

Chapter 4. The mother-in-law at the door

There is a grizzled old woman at the door of the kindergarten, where she stands every day, rain or shine, selling junk food that is about to expire. As a result of old age, the brain is a little confused, often do not know how much money he earned. One day, she overheard Xiao Ming bragging to his friends about how he would fight wits and courage with the help of Xiao Hong. So, the mother-in-law decided to find a small red card super calculator to do their own little helper, and provide 1 bao wei dragon spicy dry tofu as a reward. Xiao Hong succumbed to the temptation and agreed.

Looking back at the code in chapter 1 above, we find that the parameters of the add method of the little red card super calculator are two integer variables and one Student object. However, the old woman is not a student, but a peddler, so she must be modified here. In this case, we naturally think of inheritance and polymorphism. If xiao Ming, a student, and the old woman, a peddler, inherit from a parent class, we only need to pass in a reference to a parent class for the little red card super calculator.

In practice, however, given the single inheritance of java and the fact that you don't want to leak too much of yourself to others, you use inheritance from the interface in conjunction with inner classes.

Little red, in other words, hope to continue to provide computing services to the children in the class, and at the same time can also provide accounting services to old woman, even after can extend to other people's business, so she agreed a way to all customers, used in the processing of series 1, which is you need the operands and after I finish calculate how to do it. This unified method, Xiao Hong made an interface, provided to everyone, the code is as follows:


public class Test
 {
  public static void main(String[] args)
  {
  int a = 1;
   int b = 1;
   Student s = new Student(" Xiao Ming ");
   s.fillBlank(a, b);
  }
 }
1

As inspiration comes from filling in the blanks for Xiao Ming, Xiao Hong retains her original intention to do all the business as filling in the blanks (fillBlank).

At the same time, Xiao Hong modified her calculator to handle different people implementing the doJob interface at the same time, as follows:


public class Test
 {
  public static void main(String[] args)
  {
  int a = 1;
   int b = 1;
   Student s = new Student(" Xiao Ming ");
   s.fillBlank(a, b);
  }
 }
2

After Xiao Ming and the old woman get this interface, as long as the interface is implemented, it is equivalent to telling Xiao Hong how to deal with the result in accordance with the model of Unity 1. Do it according to the internal class mentioned before, and the code is as follows:

Xiao Ming:


public class Student
 {
  private String name = null;

  public Student(String name)
  {
   // TODO Auto-generated constructor stub
   this.name = name;
  }

  public void setName(String name)
  {
   this.name = name;
  }

  public class doHomeWork implements doJob
  {

   @Override
   public void fillBlank(int a, int b, int result)
   {
    // TODO Auto-generated method stub
    System.out.println(name + " Ask Xiao Hong for help :" + a + " + " + b + " = " + result);
   }

  }

  public void callHelp (int a, int b)
  {
   new SuperCalculator().add(a, b, new doHomeWork());
  }
 }

The old woman's:


public class Test
 {
  public static void main(String[] args)
  {
  int a = 1;
   int b = 1;
   Student s = new Student(" Xiao Ming ");
   s.fillBlank(a, b);
  }
 }
4

The test procedure is as follows:


public class Test
 {
  public static void main(String[] args)
  {
  int a = 1;
   int b = 1;
   Student s = new Student(" Xiao Ming ");
   s.fillBlank(a, b);
  }
 }
5

The results are as follows:


public class Test
 {
  public static void main(String[] args)
  {
  int a = 1;
   int b = 1;
   Student s = new Student(" Xiao Ming ");
   s.fillBlank(a, b);
  }
 }
6

The last word

It is obvious that Xiao Hong has taken this as a career, as evidenced by her name doJob.

Some people may ask, why does the old woman make so much money setting up a stall? You have a problem with your focus!! This is about callback mechanism!!

All I know is that Xiao Hong's business expanded and she finally bought her first house with the money she earned before she graduated from kindergarten.

Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: