"Reprint" Java callback mechanism (CallBack) detailed

Source: Internet
Author: User
Tags ming

Reprinted from Http://www.cnblogs.com/heshuchao/p/5376298.html

Preface

Recently studied Java, and contacted the callback mechanism (CallBack). The first knowledge of the feeling is more chaotic, but also in the online search for the relevant explanations, either a word, or the more simple as the callback made a definition. Of course, after I understood the callback, I went to see the various explanations on the Internet, and there was really no problem. However, for beginners, I lack of a gradual process. Here, my personal understanding of the callback mechanism, according to the order from the shallow to deep description, if there is something wrong, I hope to enlighten!

Before you begin, imagine a scene: Kindergarten children have just learned to add within 10.

1th Chapter. The origin of the story

Kindergarten teacher on the blackboard to write a formula "1 + 1 =", by Xiao Ming students to fill in the blanks.

Because has learned 10 within the addition, Xiao Ming students can rely entirely on their own to calculate the problem, 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     public     void SetName (String name)     {13         this.name = name;14     } +     private int calcadd (int a, int b)         + {return a + b;19}20 public     void  Fillblank (int A, int b) (int.),         result = Calcadd (A, B),         System.out.println (name + "mental Arithmetic:" + A + "+" + B + "=" + result);     }26}

Xiao Ming students in the blanks (Fillbalnk), the direct mental Arithmetic (clacadd) a bit, the result is 2, and the results are written in the space. 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 ("Xiaoming"); 8         S.fillblank (A, b); 9     }10}

The results of the operation are as follows:

Xiao Ming's mental Arithmetic: 1 + 1 = 2

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

2nd Chapter. The fault of kindergarten teachers

During recess, the teacher's whim on the blackboard wrote "168 + 291 =" Let Xiao Ming finish, and then back to the office.

Flower Rub! Why do all the teachers have to do with Xiao Ming? Clearly super-outline of the good or bad! At this time, Xiao Ming students obviously can not be like the above by mental arithmetic to complete, is in a while, the class of the little red students handed over a calculator can only calculate the addition (unscrupulous businessmen AH)!!!! Xiao Ming's classmates just know how to use the calculator, so through the calculator to obtain the results and completed the blanks.

The code for the calculator is:

1 public class Calculator2 {3 public     int Add (int a, int b) 4     {5         return a + b;6     }7}

Modify the Student class to add a method that uses the 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     public     void SetName (String name)     {13         this.name = name;14     }     @SuppressWarnings ("unused"), the     private int calcadd (int a, int b),     {a         + b;20< C17/>}21     -     private int usecalculator (int a, int b),     {         Calculator (). Add (A, b); 25     }26     public     void Fillblank (int a, int b) (int.),         result = Usecalculator (A, b);         SYSTEM.OUT.PRINTLN (name + "Use Calculator:" + A + "+" + B + "=" + result);     }32}

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         S tudent s = new Student ("Xiaoming"); 8         S.fillblank (A, b); 9     }10}

The results of the operation are as follows:

Xiaoming Use Calculator: 168 + 291 = 459

The callback mechanism is still not involved in the process, but some of Xiaoming's work has been transferred, which is assisted by the calculator.

3. Kindergarten teachers are back.

Found that Xiao Ming completed the 3-digit addition, the teacher thought Xiaoming is very clever, is a plastic. Then wrote on the blackboard "26549 + 16487 =", let Xiao Ming completed the blanks before class, and then back to the office.

Xiao Ming looked outside the classroom Sahuan son's small partner, can not help but Welling. Do not go out to play, this recess will be ruined AH!!!! Look at Little Red again handed up the calculator, Xiao Ming heart Born A: let Little red do.

Xiaoming told Xiao Red that the topic was "26549 + 16487 =" And then pointed out the exact location of the results, then went out to play happily.

Here, do not put the small red alone, but this can only calculate the addition of the calculator and Little red as a whole, a will calculate the results will also fill in the blanks of the Super calculator. This super calculator need to pass the parameter is two addend and to fill in the blanks, and these need to inform in advance, that is, Xiao Ming to his own part of the method of the storm to the small red, the simplest way is to put their references and two addend a piece to tell Xiao Red.

Therefore, the Add method of the Super calculator should contain two operands and Xiaoming's own reference, the code is as follows:

1 public class SuperCalculator2 {3 public     void Add (int a, int b, Student  xiaoming) 4     {5         int result = a + B; 6         Xiaoming.fillblank (A, B, result); 7     }8}

Xiao Ming's side now no need to do mental arithmetic, and do not need to use a calculator, so only need to have a way to the little red to ask for help on the line, the code is as follows:

1 public class Student 2 {3     private String name = NULL, 4  5 public     Student (String name) 6     {7         /T ODO auto-generated Constructor stub 8         this.name = name; 9     }10 one public     void SetName (String name) 12< c17/>{13         this.name = name;14     }15     -public void callhelp (int a, int b) +     {         new Supercalculator (). Add (A, B, this),     }20 public     void Fillblank (int a, int b, int result),     {23< C28/>SYSTEM.OUT.PRINTLN (name + "Help Little Red Calculation:" + A + "+" + B + "=" + result);     }25}

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 ("Xiaoming"); 8         S.callhelp (A, b); 9     }10}

The result of the operation is:

Xiao Ming help Xiao Red calculation: 26549 + 16487 = 43036

The execution process is: Xiao Ming through his own callhelp method called the Red (New Supercalculator ()) of the Add method, at the time of invocation of its own reference (this) as a parameter, and Little red after using the calculator to obtain the results, The Fillblank method of Xiao Ming was recalled, and the result was filled in the blank space on the blackboard.

Light Lights! Here, the callback function formally appeared, Xiaoming's Fillblank method is we often say the callback function.

Through this way, it can be obvious that the task of completing the teacher's fill in the blanks, Xiaoming has no need to wait until the addition finished and the results fill in the blackboard to go with the small partners Sahuan, fill in the blanks this work by the Super Calculator Little Red to do. The advantages of the callback have already begun to manifest.

4th chapter. The mother in the doorway

There is a gray-haired old woman at the front door of the kindergarten, where she stalls selling some junk food that is almost out of date every day. Because of the old age, the brain is a little confused, often not clear how much money he earned. One day, she overheard Xiao Ming and small friends brag about how to help Xiao Red with the teacher's wits. So, her mother-in-law decided to find the red card Super Calculator to do their own small helper, and provide a package of dragon hot strips as a reward. The Little Red scripture cannot resist the temptation, promised.

Looking back at the code in the previous chapter, we found that the Add method of the red card supercomputer requires two integer variables and a student object, but she is not a student, but she is a small trader. In this case, it is natural for us to think of inheritance and polymorphism. If we let Xiao Ming, the student and the old lady, to inherit from a parent class, then we just need to pass the red card Super Calculator to a reference to the parent class.

However, in practical use, considering the single inheritance of Java, and do not want to put too much of their own things to the others, this is used from the interface inherited from the way to do with the inner class.

In other words, Little Red hopes to continue to provide computing services to the children in the class, but also to the old woman to provide accounts services, and even later to expand the business of others, so she agreed to all the customers a method for the unified processing, that is, the number of operations they need and how to do after the calculation should be done. This unified approach, Little red made an interface, provided to everyone, the code is as follows:

1 public interface DoJob2 {3 public     void Fillblank (int a, int b, int result); 4}

Because the inspiration is to help Xiao Ming fill in the blanks, so Xiao Red retained the beginner's mind, all the business as a blank (Fillblank) to do.

At the same time, Little Red modified its own calculator, so that it can simultaneously handle different implementations of the Dojob interface of the person, the code is as follows:

1 public class SuperCalculator2 {3 public     void Add (int a, int b, dojob  customer) 4     {5         int result = a + b;6< C4/>customer.fillblank (A, B, result); 7     }8}

Xiao Ming and the old woman to get this interface, as long as the implementation of this interface, it is equivalent to follow the unified pattern to tell little red to get results after the processing method, according to the previous use of internal classes to do, the code is as follows:

Xiao Ming's:

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     public     void SetName (String name)     {13         this.name = name;14     } Public     class Dohomework implements DOJOB17     {         @Override20 public         void Fillblank ( int a, int b, int result)         {             //TODO auto-generated method stub23             System.out.println (name + "Help Little Red calculation:" + A + "+" + B + "=" + result);         }25     }27-public     void callhelp (int a, int b)     {30
   new Supercalculator (). Add (A, B, new Dohomework ());     }32}

Granny's:

1 public class Seller 2 {3     private String name = NULL, 4  5 public     Seller (String name) 6     {7         //TODO A uto-generated constructor stub 8         this.name = name; 9     }10     public     void SetName (String name)     {13< C10/>this.name = name;14     }15     Public     class Dohomework implements DOJOB17     {         @ OVERRIDE20 public         void Fillblank (int a, int b, int result)         {             //TODO auto-generated method stub23
   
    SYSTEM.OUT.PRINTLN (name + "Help Little Red Reckoning:" + A + "+" + B + "=" + result + "Yuan");         }25     }27     LIC void Callhelp (int a, int b),     {         new Supercalculator (). Add (A, B, new Dohomework ());     }32}
   

The test procedure is as follows:

1 public class Test 2 {3 public     static void Main (string[] args) 4     {5         int a =; 6         int b = +; 7         int c = 26497; 8         int d = 11256; 9         Student s1 = new Student ("Xiaoming"),         Seller s2 = new Seller ("Granny");         S1.callhelp (A , b);         s2.callhelp (c, D);     }15}

The results of the operation are as follows:

Xiao Ming help Xiao Red calculation: 56 + 31 = 87 Old lady Help Little Red reckoning: 26497 + 11256 = 37753 yuan

Last Words

Can obviously see, Little red has to this thing as a career to do, see her to interface life name Dojob know.

Some may ask, why do the old lady make so much money on the stall? There's something wrong with your attention, okay? Here is the callback mechanism AH!!

I only know, then the small red business continues to expand, finally in kindergarten before graduating, with earned money to buy the first house of life.

Finish!!!

 

"Reprint" Java callback mechanism (CallBack) detailed

Related Article

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.