Preface
CallBack means callback. People who are familiar with Windows programming must be familiar with the four words "callback function", but Java programmers may not know much about it. "Callback function" or "Callback method" is a very important concept in software design and development. It is very necessary for programmers (regardless of which language).
Recently, I learned Java and came into contact with the callback mechanism (CallBack). When I first met, I felt quite confused, and the relevant explanations I searched for online were either just mentioned or said simply, as if I had defined CallBack. Of course, after I understood the callback, I went to read the various explanations online, and there was no problem. However, for me who is a beginner, I lack a gradual process. Here, I will describe my personal understanding of the callback mechanism in the order from shallow to deep. If there is any inappropriateness, I hope I will give you advice!
Before starting, imagine a scenario: kindergarten children have just learned addition within 10.
Chapter 1. The origin of the story
The kindergarten teacher wrote a formula "1 + 1 = " on the blackboard, and Xiao Ming would fill in the blanks.
Since I have learned addition of less than 10, Xiao Ming can calculate this question entirely 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 stubthis.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, he directly calculated the clacADD and found that the result was 2 and wrote the result in the space. 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 operation results are as follows:
Xiao Ming’s 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 search for trouble for kindergarten teachers
During the break, the kindergarten teacher suddenly had a whim and wrote "168 + 291 =" on the blackboard to let Xiao Ming complete it, and then returned to the office.
Flower rub! Why can’t all teachers get along with Xiao Ming? It's obviously beyond the rules, okay? At this time, Xiao Ming obviously could not complete it by mental arithmetic like the one above. When he was confused, Xiao Hong in the class handed over a calculator that could only calculate addition (a profiteer)! ! ! ! Xiao Ming happened to know how to use a calculator, so he calculated the results through the calculator and completed the fill-in-the-blanks.
The code for the calculator is:
public class Calculator{public int add(int a, int b){return a + b;}} Modify the Student class and add a method to use the calculator:
public class Student{private String name = null;public Student(String name){// TODO Auto-generated constructor stubthis.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 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 operation results are as follows:
Xiao Ming uses calculator: 168 + 291 = 459
The callback mechanism has not been involved in this process, but some of Xiao Ming's work has been transferred and will be assisted by the calculator.
3. The kindergarten teacher is back
When I found that Xiao Ming had completed the addition of 3 digits, the teacher thought Xiao Ming was very smart and a malleable talent. So he wrote "26549 + 16487 =" on the blackboard, asking Xiao Ming to complete the fill-in-the-blanks before class, and then returned to the office.
Xiao Ming looked at the little friend who was having fun outside the classroom and couldn't help but feel sad. If you don’t go out to play, this break will be ruined! ! ! ! Looking at the calculator that Xiaohong handed it over again, Xiao Ming came up with a plan: Let Xiaohong do it for him.
Xiao Ming told Xiaohong that the question was "26549 + 16487 =", then pointed out the specific location for filling in the results, and then went out to have fun.
Here, we do not implement Xiaohong alone, but regard this calculator that can only calculate addition and Xiaohong as a whole, a super calculator that can calculate the results and fill in the blanks. The parameters that this super calculator needs to pass are the two additions and the position to fill in the blanks, and these contents need to be informed in advance, that is, Xiao Ming wants to expose part of his methods to Xiao Hong. The easiest way is to tell Xiao Hong his reference and the two additions together.
Therefore, the add method of the supercalculator should contain two operands and a reference to Xiao Ming itself, 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 no longer needs mental arithmetic or calculator, so he only needs to have a method to ask Xiaohong for help. The code is as follows:
public class Student{private String name = null;public Student(String name){// TODO Auto-generated constructor stubthis.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 + "Seeking for Xiaohong Calculation:" + 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 asked for help Xiaohong to calculate: 26549 + 16487 = 43036
The execution process is: Xiao Ming calls the add method of Xiaohong (new SuperCalculator()) through his own callHelp method, and references his own reference when calling.
(this) Pass it in as a parameter. After Xiaohong used the calculator to obtain the result, he called back Xiao Ming's fillBlank method and filled the result in the space on the blackboard.
Lights and lights! At this point, the callback function officially debuted. Xiao Ming's fillBlank method is what we often callback function.
In this way, it can be clearly seen that Xiao Ming no longer needs to wait until the addition is completed and the result is filled on the blackboard before he can have fun with his friends. The filling-in-the-blank work is done by Xiaohong, the super calculator. The advantages of callbacks have begun to be reflected.
Chapter 4. The mother-in-law at the door
There is an old lady with gray hair at the entrance of the kindergarten. She set up a street stall there selling some junk food that is almost expired every day regardless of wind and rain. Because I am old, my mind is a little confused and I often can't figure out how much money I have earned. One day, she accidentally heard Xiao Ming brag about how she fought wits and courage with the kindergarten teacher with the help of Xiaohong. So, my mother-in-law decided to find the Little Red Card Super Calculator to be her little helper and provide a pack of Weilong spicy strips as a reward. Xiaohong couldn't resist the temptation and agreed.
Looking back at the code in the previous chapter, we found that the parameters required by the add method of the Little Red Card Super Calculator are two integer variables and a Student object, but the old lady is not a student, but a small vendor, so she must make modifications here. In this case, it is natural for us to think of inheritance and polymorphism. If we ask the student Xiao Ming and the vendor of old lady to inherit from a parent class, then we only need to pass a reference to the parent class to the Little Red Card Super Calculator.
However, in actual use, considering the single inheritance of Java and not wanting to expose too much of itself to others, we use the method of inheriting from the interface to cooperate with internal classes.
In other words, Xiaohong hopes to continue to provide calculation services to the children in the class in the future, and at the same time provide accounting services to the old lady, and even expand other people's business in the future. So she agreed with all customers a method for unified processing, that is, the operands she needs and how to do it after completing the calculation. Xiaohong made this unified method into an interface and provided to everyone, the code is as follows:
public interface doJob{public void fillBlank(int a, int b, int result);} Because the inspiration came from helping Xiao Ming fill in the blanks, Xiaohong retained her original intention and treated all her business as fillBlank.
At the same time, Xiaohong modified his calculator so that it can handle different people who implement the doJob interface at the same time. 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 lady got this interface, as long as they implemented this interface, it is equivalent to telling Xiaohong the way to handle the results in a unified model, and using internal classes as mentioned earlier. The code is as follows:
Xiao Ming's:
public class Student{private String name = null;public Student(String name){// TODO Auto-generated constructor stubthis.name = name;}public void setName(String name){this.name = name;}public class doHomeWork implements doJob{@Overridepublic void fillBlank(int a, int b, int result){// TODO Auto-generated method stubSystem.out.println(name + "Seeking for Xiaohong Calculation:" + a + " + " + b + " = " + result);}}public void callHelp (int a, int b){new SuperCalculator().add(a, b, new doHomeWork());}} Old lady's:
public class Seller{private String name = null;public Seller(String name){// TODO Auto-generated constructor stubthis.name = name;}public void setName(String name){this.name = name;}public class doHomeWork implements doJob{@Overridepublic void fillBlank(int a, int b, int result){// TODO Auto-generated method stubSystem.out.println(name + "Seeking help Xiaohong to settle accounts:" + a + " + " + b + " = " + result + "Meta");}}public void callHelp (int a, int b){new SuperCalculator().add(a, b, new doHomeWork());}} The test procedure is as follows:
public class Test{public static void main(String[] args){int a = ;int b = ;int c = ;int d = ;Student s = new Student("Xiao Ming");Seller s = new Seller("Grandma");s.callHelp(a, b);s.callHelp(c, d);}} The operation results are as follows:
Xiao Ming asked for help Xiaohong to calculate: 56 + 31 = 87
The old lady asks for help from Xiaohong to settle accounts: 26497 + 11256 = 37753 yuan
The last words
It can be clearly seen that Xiaohong has already treated this matter as a career, and you will know it by looking at the name she gave the interface doJob.
Some people may ask, why can an old lady make so much money by setting up a stall? Is there any problem with your focus? ! What we are talking about here is the callback mechanism! !
All I know is that Xiaohong's business continued to expand later, and before graduating from kindergarten, she finally bought her first house in her life with the money she earned.