The JAVA CallBack mechanism, CallBack

The preface

Learning Java recently, I came into contact with the CallBack mechanism. I felt confused when I first met her, and the related explanations I found on the Internet either mentioned in a word or simply defined CallBack. Of course, after I understand the callback, I read various explanations on the Internet, there is no problem. However, for the beginner of me, the lack of a gradual process. Here, will be my personal understanding of the callback mechanism, according to the order from shallow to deep description, if there is anything wrong, please feel free to comment!

To begin, imagine a scenario: kindergarteners have just learned to add up to 10.

Chapter 1. The Origin of the story

The teacher wrote a formula “1 + 1 =” on the blackboard, xiaoming students to fill in the blanks.

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

 1 public class Student 2 {
 3     private String name = null;
 4 
 5     public Student(String name) 6     {
 7         // TODO Auto-generated constructor stub
 8         this.name = name; 9 } 10     
11     public void setName(String name) 12 { 13         this.name = name; 14 } 15     
16     private int calcADD(int a, int b) 17 { 18         return a + b; 19 } 20     
21     public void fillBlank(int a, int b) 22 { 23         int result = calcADD(a, b); 24         System.out.println(name + "Mental arithmetic." + a + "+" + b + "=" + result); 25 } 26 }</pre>
Copy the code

When xiao Ming filled in the blanks, he did some calculations in his head and got the result 2. He wrote the result in the blank. The test code is as follows:

 1 public class Test 2 {
 3     public static void main(String[] args) 4     {
 5         int a = 1;
 6         int b = 1;
 7         Student s = new Student("Xiao Ming");
 8         s.fillBlank(a, b);
 9 } 10 }</pre>

Copy the code

The running results are as follows:

Xiao Ming did mental arithmetic:1 + 1 = 2</pre>
Copy the code

This process is done entirely by instance objects of the Student class alone, and no callback mechanism is involved.

Chapter 2. The young teacher to find fault

During the break, the kindergarten teacher suddenly wrote on the blackboard “168 + 291 =” let Xiaoming complete, and then back to the office.

Flower brush! Why do all the teachers have it in for Xiao Ming? Clearly beyond the outline good! At this time xiaoming students obviously can no longer like the above by mental calculation to complete, is meng force of the time, the class of small red students handed over a calculator can only calculate addition (unprofitable ah) !!!! Xiao Ming knew exactly how to use a calculator, so he got the result by calculator and finished filling in the blanks.

The code for the calculator is:

1 public class Calculator 2 { 3     public int add(int a, int b) 4 { 5         return a + b; 6 } 7 }</pre>

Copy the code

Modify the Student class to add a method that uses a calculator:

1 public class Student 2 {
 3     private String name = null;
 4 
 5     public Student(String name) 6     {
 7         // TODO Auto-generated constructor stub
 8         this.name = name; 9 } 10     
11     public void setName(String name) 12 { 13         this.name = name; 14 } 15     
16     @SuppressWarnings("unused") 17     private int calcADD(int a, int b) 18 { 19         return a + b; 20 } 21     
22     private int useCalculator(int a, int b) 23 { 24         return new Calculator().add(a, b); 25 } 26     
27     public void fillBlank(int a, int b) 28 { 29         int result = useCalculator(a, b); 30         System.out.println(name + "Use a calculator :" + a + "+" + b + "=" + result); 31 } 32 }</pre>

Copy the code

The test code is as follows:

 1 public class Test 2 {
 3     public static void main(String[] args) 4     {
 5         int a = 168;
 6         int b = 291;
 7         Student s = new Student("Xiao Ming");
 8         s.fillBlank(a, b);
 9 } 10 }</pre>
Copy the code

The running results are as follows:

Xiao Ming uses a calculator:168 + 291 = 459</pre>
Copy the code

There is still no callback mechanism involved in this process, but part of Xiaoming’s work has been transferred to the calculator to help achieve. [Obtaining resources]

Chapter 3. The kindergarten teacher comes back

When xiao Ming finished adding three digits, the teacher thought xiao Ming was very smart and a malleable talent. So he wrote “26549 + 16487 =” on the blackboard, and let Xiao Ming finish filling in the blanks before class, and then went back to the office.

Xiao Ming looked at his friends outside the classroom and felt sad. Don’t go out to play again, this break is about to waste !!!! Looking at the calculator handed by Xiao Hong again, Xiao Ming had an idea: Let Xiao Hong do it for him.

Xiao Ming told Xiao Hong that the topic was “26549 + 16487 =”, and then pointed out the specific position of filling in the results, and then went out to play happily.

Here, instead of implementing red by itself, we’re going to think of this calculator that can only add and red as a whole, a super calculator that can do results and fill in the blanks. The parameters of this super calculator need to be passed are two addendums 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 expose part of his method to Xiao Hong, the simplest way is to tell Xiao Hong together with his own citation and two addendums. [Obtaining resources]

Therefore, the supercalculator’s add method should contain two operands and a reference to xiaoming itself, as follows:

1 public class SuperCalculator 2 { 3     public void add(int a, int b, Student  xiaoming) 4 { 5         int result = a + b; 6 xiaoming.fillBlank(a, b, result); 7 } 8 }</pre>

Copy the code

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

 1 public class Student 2 {
 3     private String name = null;
 4 
 5     public Student(String name) 6     {
 7         // TODO Auto-generated constructor stub
 8         this.name = name; 9 } 10     
11     public void setName(String name) 12 { 13         this.name = name; 14 } 15     
16     public void callHelp (int a, int b) 17 { 18         new SuperCalculator().add(a, b, this); 19 } 20     
21     public void fillBlank(int a, int b, int result) 22 { 23         System.out.println(name + "Ask Little Red to calculate :" + a + "+" + b + "=" + result); 24 } 25 }</pre>

Copy the code

The test code is as follows:

1 public class Test 2 {
 3     public static void main(String[] args) 4     {
 5         int a = 26549;
 6         int b = 16487;
 7         Student s = new Student("Xiao Ming");
 8         s.callHelp(a, b);
 9 } 10 }</pre>

Copy the code

The running results are as follows:

Xiao Ming asks Xiao Hong for help to calculate:26549 + 16487 = 43036</pre>
Copy the code

The execution process is as follows: Xiao Ming called The add method of Xiao Ming (newSuperCalculator()) through his callHelp method, passing in his reference (this) as a parameter during the call, and Xiao Hong called back Ming’s fillBlank method after using the calculator to get the result. Fill in the blanks on the blackboard.

Light lamp light! Here, the callback function officially came on stage, Xiao Ming’s fillBlank method is often called the callback function.

In this way, it is obvious that Xiao Ming no longer needs to wait until the addition is finished and the result is filled in on the blackboard before he can go to play with his friends. Xiao Hong, the super calculator, can fill in the blanks. The advantages of a pullback are already being felt. [Obtaining resources]

Chapter 4. Mother-in-law at the door

At the gate of the kindergarten is a gray-haired old woman who stands selling junk food that is about to expire every day, come rain or shine. Because of old age, the brain is a little confused, often can not figure out how much money he earned. One day, she overhears Xiao Ming bragging to his friends about how he fought with his teacher with the help of Xiao Hong. So, the mother-in-law decided to find a little red card super calculator to do their own little help, and offered a package of Wei Long spicy sticks as a reward. Xiao Hong could not resist the temptation and agreed.

Looking back at the code in the previous chapter, we can see that the add method of the red card supercalculator requires two integer variables and a Student object, but the old lady is not a Student, she is a small vendor, there must be a change here. In this case, it’s natural to think about inheritance and polymorphism. If xiaoming, the student, and the old woman, the peddler, inherit from a parent class, all we need to do is pass in a reference to the parent class to the little Red card super calculator.

In practice, however, given Java’s single inheritance and the fact that you don’t want to expose too much of yourself to others, you use interface inheritance 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, for unified handling, also is the operand you need and what do I do after I finish calculate. This unified method, Xiao Hong made an interface, provided to everyone, the code is as follows:

1 public interface doJob 2 { 3     public void fillBlank(int a, int b, int result); 4 }</pre>
Copy the code

Inspired by helping Ming fill in the blanks, Xiao Hong retains her original intention and treats all her business as fillBlank. [Obtaining resources]

At the same time, Xiao Hong modified her calculator so that it can handle different people who implement doJob interface at the same time. The code is as follows:

1 public class SuperCalculator 2 { 3     public void add(int a, int b, doJob  customer) 4 { 5         int result = a + b; 6 customer.fillBlank(a, b, result); 7 } 8 }</pre>
Copy the code

Xiao Ming and the old woman get this interface, as long as the implementation of the interface, it is equivalent to a unified mode to tell Xiao Hong after the results of the treatment, according to the use of internal classes to do, the code is as follows:

Xiao Ming:

 1 public class Student 2 {
 3     private String name = null;
 4 
 5     public Student(String name) 6     {
 7         // TODO Auto-generated constructor stub
 8         this.name = name; 9 } 10     
11     public void setName(String name) 12 { 13         this.name = name; 14 } 15     
16     public class doHomeWork implements doJob 17 { 18 
19 @Override 20         public void fillBlank(int a, int b, int result) 21 { 22             // TODO Auto-generated method stub
23             System.out.println(name + "Ask Little Red to calculate :" + a + "+" + b + "=" + result); 24 } 25         
26 } 27     
28     public void callHelp (int a, int b) 29 { 30         new SuperCalculator().add(a, b, new doHomeWork()); 31 } 32 }</pre>

Copy the code

Of an old woman:

 1 public class Seller 2 {
 3     private String name = null;
 4 
 5     public Seller(String name) 6     {
 7         // TODO Auto-generated constructor stub
 8         this.name = name; 9 } 10     
11     public void setName(String name) 12 { 13         this.name = name; 14 } 15     
16     public class doHomeWork implements doJob 17 { 18 
19 @Override 20         public void fillBlank(int a, int b, int result) 21 { 22             // TODO Auto-generated method stub
23             System.out.println(name + "Ask Xiao Hong for help :" + a + "+" + b + "=" + result + "Yuan"); 24 } 25         
26 } 27     
28     public void callHelp (int a, int b) 29 { 30         new SuperCalculator().add(a, b, new doHomeWork()); 31 } 32 }</pre>
Copy the code

The test procedure is as follows:

1 public class Test 2 {
 3     public static void main(String[] args) 4     {
 5         int a = 56;
 6         int b = 31;
 7         int c = 26497;
 8         int d = 11256;
 9         Student s1 = new Student("Xiao Ming"); 10         Seller s2 = new Seller("Old woman"); 11         
12 s1.callHelp(a, b); 13 s2.callHelp(c, d); 14 } 15 }</pre>

Copy the code

The running results are as follows:

The old woman turned to Xiao Hong for help:26497 + 11256 = 37753Yuan < / pre >Copy the code

At the end

You can clearly see that Xiao Hong has taken this as a career, just look at her name doJob. [Obtaining resources]

Some people may ask why the old woman can earn so much money by setting up a stall? You have a problem with focus!! This is the callback mechanism!!

All I know is that xiao Hong’s business continued to expand and she finally bought her first house with the money she earned before she graduated from kindergarten.

Finish!!!!!!

In the end, I wish you all success as soon as possible, get satisfactory offer, fast promotion and salary increase, and walk on the peak of life.

If you can, please give me a three support me?????? [Obtain information]