The callback mechanism in Java (CallBack) _java

Source: Internet
Author: User
Tags arithmetic call back inheritance ming stub

Objective

Recently, learning Java, access to the callback mechanism (CallBack). The first time feel more confused, and in the Internet to find the relevant explanation, or a word with, or say more simple like to give callback made a definition. Of course, after I understood the callback, I went to see all kinds of explanations on the Internet, and I really didn't have any problems. However, for beginners of me, the lack of a step-by-step process.

A callback is a two-way invocation pattern, which means that the callee also invokes the other when called , which is called a callback. "If You call me, I'll call back."

Don't understand? That's okay, let's take a look at this. The classic way to use callbacks:

Class A implements interface ina--background 1

Class A contains a reference to Class B b--background 2

Class B has a method with a parameter of INA test (ina a)--background 3

A's object A calls the method of B to pass to itself, test (a)--this step is equivalent to the call me

B can then invoke the INA method in the test method--This step is equivalent to I call your back

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

Below, my personal understanding of the callback mechanism, in accordance with the order of the shallow to deep description, if there is something wrong, look at the generous enlighten!

1th Chapter. The origin of the story

Teachers in the blackboard to write a formula "1 + 1 =", by xiaoming students to fill in the blanks.

As has been studied within 10 of the addition, xiaoming students can rely on their own to calculate the problem, simulation of the process code 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 = Calcadd (A, b);
   SYSTEM.OUT.PRINTLN (name + "mental Arithmetic:" + A + "+" + B + "=" + result);
  }
 

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

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 , and does not involve a callback mechanism.

2nd Chapter. The fault of kindergarten teachers

At recess, kindergarten teachers on the blackboard on the whim of "168 + 291 =" Let Xiao Ming finish, and then back to the office.

Flower Rub! Why do all teachers have trouble with xiaoming? Clearly the outline of the good! At this time xiaoming students obviously can no longer like the above by mental arithmetic to complete, is a Meng force, the class of little red classmate handed over a calculator can only calculate addition (profiteers AH)!!!! And Xiao Ming students just know how to use the calculator, so through the calculator to calculate the results 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 to add a method to use 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 = 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 = 291;
   Student s = new Student ("Xiaoming");
   S.fillblank (A, b);
  }
 

The results of the operation are as follows:

Xiaoming uses calculator: 168 + 291 = 459

The callback mechanism is still not involved in this process, but some of Xiaoming's work has been transferred, and the calculator is helping to implement it.

3. Kindergarten teachers are back

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

Xiao Ming looked at the classroom outside Sahuan son's small partner, cannot help Welling. Don't go out to play, this recess will be abolished AH!!!! Looking at the small red once again handed up the calculator, xiaoming heart of a plan: let Little Red to do.

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

Here, do not make small red alone to realize, but the calculator that can only count addition and small red as a whole, a will calculate the result will also fill in the blank of Super Calculator. The super calculator needs to pass the parameter is two addends and to fill in the blank position, but these contents need xiaoming to inform in advance, that is Xiaoming wants to put one part of his method to the small red, the simplest method is to own the reference and two a addends piece tells the small red.

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

public class Supercalculator
 {public
  void Add (int a, int b, Student xiaoming)
  {
   int = a + b;
   Xiaoming.fillblank (A, B, result);
  }
 

Xiao Ming here now do not need to do mental arithmetic, also do not need to use a calculator, so just have a way to red to seek help on the line, 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 results)
  {
   System.out.println (name + "Help Little Red": "+ 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 ("Xiaoming");
   S.callhelp (A, b);
  }
 

The results of the operation are:

Xiao-ming for help Xiao Hong Calculation: 26549 + 16487 = 43036

The implementation process is: Xiao Ming through its own Callhelp method called the Red (new SuperCalculator()) Add method, in the call of its own reference (this) as a parameter, the red in the use of calculators to draw results, the callback of Xiaoming's Fillblank method, the results are filled in the blanks on the blackboard.

Lights, lights, lights! Here, the callback function is officially on the scene, Xiaoming's Fillblank method is we often say the callback function.

In this way, it can be clearly seen, for the completion of the teacher's fill in the blank question this task, xiaoming has no need to wait to add to finish and the results filled on the blackboard to go with the small partners Sahuan, fill in the blank this work by Super Calculator Xiao Red to do. The advantages of a callback are already beginning to manifest.

4th chapter. The mother-in-law at the door

There is a gray-haired old lady at the entrance to the kindergarten, where every day, rain or shine, there are stalls selling junk food that is fast overdue. Because of his old age, his brain is a bit confused and often not sure how much money he earns. One day, she accidentally heard Xiao Ming and small partners boast about how in small red with the help of kindergarten teacher wits. So the mother-in-law decided to find a small red card super Calculator to do their own small helper, and provide a pack of Dragon hot strips as a reward. Little Red could not resist the temptation to say yes.

Looking back at the code in the previous chapter, we found that the Add method for the small red card supercomputer requires two integer variables and a student object , but she's not a student, she's a small trader, and it's definitely going to be modified here. In this case, we will naturally think of inheritance and polymorphism. If let xiaoming this student and the old lady this small merchant inherits from a parent class, then we only need to give the small red card Super Calculator to pass a reference to a parent class.

However, in actual use, considering the single inheritance of Java and not wanting to throw too much of itself into others, this is done in conjunction with the inner class in a way that inherits from the interface.

In other words, Xiao Hong hopes to continue to provide computing services to the class's children in the future, at the same time, the elderly can also provide the accounts of the service, and even later to expand the business of others, so she agreed to all customers a solution for the unified processing, that is, the number of operations they need to do after the calculation should be done. This unified approach, little Red made up an interface, provided to everyone, the code is as follows:

Public interface Dojob
 {public
  void Fillblank (int a, int b, int result);
 }

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

At the same time, Little Red modifies its own calculator so that it can handle different people who implement the Dojob interface , as follows:

public class Supercalculator
 {public
  void Add (int a, int B, dojob customer)
  {
   int result = a + b;
   Customer.fillblank (A, B, result);
  }
 

Xiaoming and the old lady to get this interface, as long as the implementation of this interface, is equivalent to the uniform mode to tell the results of the treatment after the red, according to the previous use of internal classes to do, the code is as follows:
Xiao Ming's:

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 + "Help Little Red Compute:" + A + "+" + B + "=" + result); 
   
    }

  public

  void Callhelp (int a, int b)
  {
   new Supercalculator (). Add (A, B, new Dohomework ());
 }
   

Granny's:

public class Seller
{
 private String name = NULL;

 Public Seller (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 + "Help Little Red Accounts:" + A + "+" + B + "=" + result + "Yuan") ;
  }

 }

 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 = 26497;
  int d = 11256;
  Student S1 = new Student ("Xiaoming");
  Seller s2 = new Seller ("Granny");

  S1.callhelp (A, b);
  S2.callhelp (c, D);
 }

The results of the operation are as follows:

Xiao-ming for help Xiao Hong Calculation: 56 + 31 = 87

The old lady for help Little Red accounts: 26497 + 11256 = 37753 yuan

Summarize

It is obvious that Xiao Hong has taken this thing as a career to do, look at her to the interface of the name of life dojob know.

One might ask, why does granny make so much money on a stall? There's something wrong with your focus!! Here is the callback mechanism AH!!

I only know that later, Xiao Hong's business continued to expand, and finally before graduating from kindergarten, with the money to buy the life of the first house.

The above is this article for Java Callback mechanism (CallBack) interesting detailed explanation, hope to learn Java to help you. And thank you for your support for the cloud-dwelling community.

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.