Details of JAVA callback mechanism CallBack

  • 2020-05-09 18:35:21
  • OfStack

The preface

"CallBack" means "callback." those familiar with the programming of Windows will be familiar with the four words "callback function," but the programmers of Java may not be familiar with it. Callback function "or" callback method "is a very important concept in software design and development. It is necessary for programmers (no matter what language they use) to master the idea of" callback function ".

Recently, I learned about java and learned about the callback mechanism (CallBack). When I first met him, I felt confused. Moreover, I found relevant explanations on the Internet, which were either passed by 1 person or said something simple like a definition of CallBack. Of course, once I understand the callbacks, I don't have a problem reading the online explanations. However, as a beginner, I am missing a step by step process. Here, I will be on the callback mechanism of personal understanding, in accordance with the order from shallow to deep description 1, if there is not appropriate, please grant me!

To begin, imagine a scenario in which a kindergarten child has just learned how to add up to 10.

Chapter 1. The origin of the story

The teacher writes a formula "1 + 1 =" on the blackboard, and xiao Ming fills in the blank.

Since he has learned addition within 10, xiao Ming can calculate the problem completely 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 filling in the blank (fillBalnk), xiao Ming directly calculated in his head (clacADD) 1, and got the result is 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 = ;
int b = ;
Student s = new Student(" Xiao Ming ");
s.fillBlank(a, b);
}
}

The results are as follows:

Xiaoming did it in his head :1 + 1 = 2

This process is done solely by the instance object of the Student class, without involving a callback mechanism.

Chapter 2. Kindergarten teacher's fault finding

During the break, the kindergarten teacher had a whim to write "168 + 291 =" on the blackboard for xiao Ming to finish, and then went back to the office.

Flower brush! Why are all the teachers against xiaoming? Obviously super class good! At this time, xiao Ming can no longer rely on mental calculation as above to complete, is meng, the class of small red students pass over 1 can only calculate addition calculator (profiter ah)!!!! However, xiao Ming just knew how to use a calculator, so he calculated the result through the calculator and finished filling in the blank.

The code of the calculator is:


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

Modify the Student class to add methods to use the 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 = ;
int b = ;
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 this process, but some of xiaoming's work has been transferred and assisted by the calculator.

The kindergarten teacher is back

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

Xiao Ming looked at the small partners outside the classroom, can not help but sad. Do not go out to play, this class will be scrapped!! < / p > < p > looking at the small red once again handed up the calculator, xiaoming heart 1: let the small red.

Xiao Ming told xiao hong that the topic was "26549 + 16487 =", and then pointed out the specific position to fill in the result, and then went out to play happily.

So instead of doing this separately, we're going to look at the addition calculator and the little red as a whole, a super calculator that can do the math and fill in the blanks. The parameters of this super calculator need to be passed are two addendum and the position to fill in the blank, and these contents need to be informed in advance by xiao Ming, that is, xiao Ming should expose his 1 part of the method to xiao hong, the easiest way is to give his own reference and two addendum 1 block to xiao hong.

Therefore, the add method of the super calculator should contain two operands and a reference to xiaoming himself. The code is as follows:


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

Xiao Ming now does not need to do mental arithmetic and does not need to use a calculator. Therefore, only one method is needed 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 + " Help little red calculate :" + a + " + " + b + " = " + result);
}
} 

The test code is as follows:


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

The running result is:

Xiao Ming help xiao hong calculation :26549 + 16487 = 43036
The execution process is as follows: xiaoming calls the add method of xiaohong (new SuperCalculator()) through his callHelp method, and references himself when calling

(this) was taken as parameter 1 and passed in. After using the calculator to get the result, xiaohong called back xiaoming's fillBlank method and filled the result in the blank on the blackboard.

Light lamp light! At this point, the callback function will come into play. Xiaoming's fillBlank method is often called the callback function.

In this way, it can be seen clearly that xiao Ming does not need to wait until the addition is finished and the result is filled on the blackboard before he can have fun with his friends. The job of filling in the blanks is done by super calculator xiao hong. The advantages of the pullback are starting to show.

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

At the gate of the kindergarten, a grey-haired old woman stands on the ground every day, rain or shine, selling junk food that is about to expire. Because of old age, the brain is a little confused, often do not know how much money they earn. One day, she overheard xiao Ming bragging to his friends about how he fought with his kindergarten teacher with the help of xiao hong. So, the mother-in-law decided to find a small red card super calculator to do their little helper, and provide 1 bao wei long spicy dry tofu as a reward. Xiao hong succumbed to the temptation and agreed.

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

In practice, however, given java's single-inheritance and the fact that it doesn't want to give away too much of itself, inheritance from the interface is used in conjunction with the 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 1 method, small red made an interface, provided to you, the code is as follows:


public interface doJob
{
public void fillBlank(int a, int b, int result);
} 

Since the inspiration came from helping xiao Ming fill in the blanks, xiao hong kept her original intention and did all the business as filling in the blanks (fillBlank).

At the same time, xiao hong modified her calculator so that it can simultaneously handle different people who have implemented the doJob interface. The code is as follows:


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

After xiao Ming and the old woman get this interface, as long as the interface is realized, it is equivalent to telling xiao hong the processing method after the result is obtained according to the model of system 1, using the internal class to do according to the previous said, the code is as follows:

Xiao Ming:


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

The old woman's:


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

The test procedure is as follows:


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

The results are as follows:

Xiao Ming help xiao hong calculation :56 + 31 = 87

The old woman asked xiao hong for help: 26497 + 11256 = 37753 yuan

The last word

It can be seen clearly that xiao hong has made this a career out of it, as can be seen from the name doJob she gave to the interface.

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

All I know is that xiao hong's business kept expanding and she finally bought her first house with the money she earned before she graduated from kindergarten.


Related articles: