callback function
When it comes to callbacks, we have to start with the callback function, what is called a callback function?
What is a callback function?
Baidu Encyclopedia Explanation: The callback function is a function called through a function pointer. If you pass the pointer (address) of the function as an argument to another function, when the pointer is used to invoke the function it points to, we say this is a callback function. The callback function is not called directly by the implementing party of the function, but is called by the other party when a particular event or condition occurs, and is used to respond to the event or condition.
Next, let's briefly explain the callback function.
There are three types of modules known to the graph, at which point 2 can be called a callback function?
Answer: No, only if the label 2 function is passed as a parameter to the label 3 function, it can be called a callback function.
For example, people (like function declaration), Lao Wang (similar function definition), school (similar to the caller) three concepts, a school needs to recruit as a teacher, then Lao Wang to apply for, because Lao Wang has excellent teaching ability, the school hired Lao Wang as a senior teacher. The old King, who was successfully hired by the school, could be called a senior teacher (similar to a callback function), otherwise he was just an old king, not a senior teacher.
The mechanism of the callback function:
(1) Define a callback function;
(2) The Party providing the function implementation registers the function pointer of the callback function with the caller at initialization time;
(3) When a particular event or condition occurs, the caller uses a function pointer to invoke the callback function to process the event.
The callback function is usually at the same level as the original caller:
Why use a callback function?
Because the caller can be separated from the callee. The caller does not care who the callee is, all it needs to know, but there is a called function that has a certain prototype, some restrictions (such as a return value of int).
If you want to know what the callback function does in practice, let's assume that there is a case where we're going to write a library that provides implementations of some sort algorithms, such as bubble sort, quick sort, shell sort, shake sort, and so on, but to make the library more generic and not want to embed the sort logic in the function, And let the user implement the corresponding logic, or, you want the library to be used for a variety of data types (int, float, string), at this time, what to do? You can use a function pointer and make a callback.
Callbacks can be used to notify the mechanism, for example, sometimes to set a timer in the program, each time, the program will be notified, but the notification mechanism of the implementation of our program is ignorant . At this point, it is necessary to have a specific prototype of the function pointer, with this pointer to the callback, to notify our program event has occurred . In fact, the SetTimer () API uses a callback function to inform the timer, and in the event that a callback function is not provided, it also sends a message to the program's message queue.
Another API function that uses a callback mechanism is Enumwindow (), which enumerates all the top-level windows on the screen, invokes a program-provided function for each window, and passes the window's handlers. If the callee returns a value, the iteration continues, otherwise, exits. Enumwindow () does not care where the callee is, nor does it care what the callee does with the handlers it passes, it only cares about the return value, because it will continue to execute or exit based on the return value.
How do I use callback functions?
Using the callback function, we need to do three things:
1. Declaring a function model
2. Define function body
3. Pass the callback function as a parameter to the function that satisfies the format for the system to call.
Example 1: A C language code
#include <iostream>
using namespace Std;
//1, Statement
typedefvoid(*PF) ();
//2, definition
voidFunc ()
{
cout <<"Func"<< Endl;
}
voidCaller (PF PF)
{
PF ();
}
intMain ()
{
PF p = func;
///3, function as parameter pass
Caller (p);
System"Pause");
return0;
}
Example 2:c# code
Using System;
Using System.Runtime.InteropServices;
//1, function declaration
Publicdelegate BOOL CallBack (inthwndintLParam);
PublicclassEnumreportapp
{
[DllImport ("User32")]
PublicStaticexternintEnumWindows (CallBack x,inty);
PublicStatic voidMain ()
{
///3, function as parameter pass
CallBack Mycallback =NewCallBack (Enumreportapp.report);
EnumWindows (mycallback, 0);
}
//2, function definition
PublicStaticBOOL Report (inthwndintLParam)
{
Console.Write ("Window handle is");
Console.WriteLine (HWND);
returnTrue
}
}
From the description of the use of the callback function, we can divide the call into two parts: protocol and protocol
1. Protocol specification (function declaration)
2. Protocol implementation (function definition)
3. Call protocol (function as parameter pass, use)
Interface callbacks
Java is an object-oriented language, all objects, so there is no callback function in Java. Because everything in Java is Object nature, this feature of the callback function is raised to the interface callback.
What is an interface callback?
Interface callback: You can assign a reference to an object created by a class that uses an interface to an interface variable declared by that interface, then the interface variable can invoke the method of the interface implemented by the class. In fact, when an interface variable calls a method in an interface that is implemented by a class, it is the method that notifies the corresponding object to invoke the interface, a process called an interface callback for the object function.
As can be seen from the concept, the interface callback refers to a use process, and emphasizes the use of the object function, since it is a function, the function is generally corresponding to the method body (function), so it also satisfies the callback function similar to the model.
(1) Definition of the interface
(2) Implementation of the interface
(3) Calling interface
The reference (address) of (2) is passed to (3), and then (3) invokes the method in (2), which is called an interface callback for the object function.
The interface callback differs from the callback function: The interface callback focuses on the process, and the callback function emphasizes the function (entity).
The interface callback is the same point as the callback function: it passes the address of itself to the caller, allowing the caller to invoke the relevant method based on the address.
The personal simple understanding of the callback is: Pass your own address to me, I will call you according to your address.
The mechanism of interface callbacks is similar to the mechanism of callback functions:
(1) Define an interface;
(2) The party that provides the interface implementation registers the reference of the interface callback to the caller at initialization time;
(3) When a particular event or condition occurs, the caller processes the event using the interface method implemented by the reference call.
The benefits of interface callbacks are similar to the use of callback functions, and are not repeated here.
How do I use interface callbacks?
Interface callback, I will divide it into two ways, a push mode, a pull mode.
Push mode
The push mode of the interface callback means that party a proactively pushes its address to the caller. For example, the following example:
Interface:
Public Interface Gaslistener
{
Public void Offergas (String msg);
}
Interface implementation of the party:
PublicclassGascompanyImplementsGaslistener
{
PublicvoidAdvertiseto (Indoorsman man)
{
System.out.println ("gas Company: This is our contact information, Welcome to call!" ");
Man.setlistener ( This);
}
@Override
PublicvoidOffergas (String msg)
{
System.out.println ("The order received by the gas company:"+MSG);
}
}
Called by:
PublicclassIndoorsman
{
Gaslistener Glistener;
PublicvoidPreparecook ()
{
System.out.println ("Otaku: Prepare to cook a few fancy-style meal!" ");
System.out.println ("otaku: Into the kitchen, cooking ...");
System.out.println ("Otaku: Just opened fire, found gas shortage, no way, can only call gas." ");
Glistener.offergas ("Otaku: Send a bottle of gas over here!");
}
PublicvoidSetlistener (Gaslistener Glistener)
{
This. Glistener = Glistener;
}
}
Test:
PublicclassTest
{
PublicStaticvoidMain (string[] args)
{
Indoorsman man =NewIndoorsman ();
Gascompany Company =NewGascompany ();
Company.advertiseto (man);
Man.preparecook ();
}
}
Gascompany company in the advertising, on the initiative to inform the indoorsman of their own information, when Indoorsman found gas shortage This event occurs, Indoorsman according to the interface reference calls Gascompany services.
Pull ModeThe pull mode of the interface callback refers to the caller's own initiative to obtain the information of party A.
Called by
PublicclassIndoorsman
{
Gaslistener Glistener;
PublicvoidPreparecook ()
{
System.out.println ("Otaku: Prepare to cook a few fancy-style meal!" ");
System.out.println ("otaku: Into the kitchen, cooking ...");
System.out.println ("Otaku: Just opened fire, found gas shortage, no way, can only call gas." ");
Glistener.offergas ("Otaku: Send a bottle of gas over here!");
}
PublicvoidSetlistener (Gaslistener Glistener)
{
This. Glistener = Glistener;
}
PublicvoidConfiguregas ()
{
//Take the initiative to obtain party information
Setlistener (NewGaslistener ()
{
@Override
PublicvoidOffergas (String msg)
{
System.out.println ("Next order content:"+MSG);
}
});
}
}
Test
PublicclassTest
{
PublicStaticvoidMain (string[] args)
{
Indoorsman man =NewIndoorsman ();
Man.configuregas ();
Man.preparecook ();
}
}
For example, when threading thread is used, the implementation of the Runnable interface is often actively acquired when the thread object is built.
PublicclassTest
{
PublicStaticvoidMain (string[] args)
{
Thread thread =NewThread (NewRunnable ()
{
@Override
PublicvoidRun ()
{
}
});
}
}
Extension: The interface callback mechanism satisfies the observer design pattern, the observer registers its own address with the observer, and when an event occurs, the observer invokes the corresponding observer according to the registered address.
Reference:
1. Callback functions and function pointers
2. A classic example that gives you a thorough understanding of the Java callback mechanism
3, Java callback Mechanism (CallBack) detailed
callback function, Java interface callback summary