Java callback mechanism
Callback concept:
There are always some interfaces between software modules. In terms of calling methods, they can be divided into three types: Synchronous call, callback and asynchronous call. Synchronous call is a blocking call. The caller must wait for the execution of the other party to complete before returning. It is a one-way call. Callback is a two-way call mode, that is, the called party also calls the other party's interface when the interface is called. asynchronous call is a mechanism similar to messages or events, but its call direction is the opposite, when an interface service receives a message or an event, it proactively notifies the customer (that is, the customer's interface ). Callback and asynchronous call are closely related. Generally, callback is used to register asynchronous messages and message notifications are implemented through asynchronous calls. Synchronous calls are the simplest of the three, and callback is often the basis of asynchronous calls. JAVA Implementation callback:
Before JAVA supports method pointers, the Java interface cannot provide a good method for implementing callback. If you are used to passing function pointers called in the event-driven programming model, you will like this technique. Developers familiar with the MS-windows and X Window System event-driven programming models are used to passing function pointers that are called ("Callback") when an event occurs. Java's object-oriented model currently does not support method pointers, so it seems impossible to use such a good mechanism. But we don't have a solution!
Java interfaces support a mechanism to obtain the equivalent functions of callback. The trick is to define a simple interface and declare the method we want to call in this interface. For example, suppose we want to be notified when an event occurs. We can define an interface: public interface interestingevent
{
// This is only a common method. Therefore, if necessary,
// It can return values or receive parameters.
Public void interestingevent ();
} This allows us to control any object of the class implementing this interface. Therefore, we do not need to care about any external type information. This method is much better than using the data fields of the widget to accommodate uncontrollable c Functions of object pointers when using C ++ code for motif. The class that sends the event signal must wait for the object that implements the interestingevent interface and call the interestingevent () method as appropriate. Public class eventnotifier
{
Private interestingevent ie;
Private Boolean somethinghappened; Public eventnotifier (interestingevent event)
{
// Save the event object for future use.
Ie = event;
// No event to be reported.
Somethinghappened = false;
}
//... Public void dowork ()
{
// Check the predicates set elsewhere.
If (somethinghappened)
{
// Send an event signal by calling this method of the interface.
Ie. interestingevent ();
}
//...
}//...
} In the above example, I used the somethinghappened predicate to track whether an event should be triggered. In many cases, calling this method is sufficient to ensure that a signal is sent to interestingevent. The code for Receiving Event Notifications must implement the interestingevent interface and pass its reference to the Event Notification Program. Public class callme implements interestingevent
{
Private eventnotifier en; Public callme ()
{
// Create an event notification program and pass its reference to it.
En = new eventnotifier (this );
} // Define the actual handler for the event.
Public void interestingevent ()
{
// Oh! Events of interest must have occurred!
// Execute some operations...
}//...
} Java callback is implemented through interfaces.
Example:
1. Class A, Class B
2. Class A implements the interface operate
3. Class B has a function test (operate O) with parameters of the operate interface type)
4. Class A calls the test function in Class B during runtime, and passes in parameters as itself
5. If Class B has obtained a, it can call back the public interface boomwtc IN THE operate interface implemented by a at any time.
{
// Get Bin Laden's decision
Public benladengdecide (); // executes the bombing of World Trade Center
Public void boom ();
} Public class at $911 implements boomwtc
{
Private Boolean decide;
Private terroristattack ta; public at $911 (){
Date Now = new date ();
Simpledateformat myfmt1 = new simpledateformat ("YY/MM/dd hh: mm ");
This. dicede = myfmt. Format (DT). Equals ("01/09/11 ");
This. Ta = new terroristattack ();
} // Get Bin Laden's decision
Public Boolean benladengdecide (){
Return decide;
} // Execute the bombing of World Trade Center
Public void boom (){
Ta. Attack (New at $911 );
}
} Public class terroristattack {
Public terroristattack (){
} Public attack (boomwtc BMW ){
If (BMW. benladengdecide ()){
// Let's go .........
}
}}
========================================================== ======================================
1. What is a callback function?
A callback function, as its name implies, is a callback function. A callback function is just a function snippet that is implemented by the user according to the callback function call conventions. A callback function is a part of a workflow. The workflow determines the function call (callback) time. The callback function has the following features:
1. A part of the workflow;
2. The statement must be affirmed (defined) according to the call Conventions specified by the workflow );
3. The call time is determined by the workflow. The implementer of the callback function cannot directly call the callback function to implement the workflow function;
2. callback mechanism
The callback mechanism is a common design model. It exposes a function in a workflow to external users according to the agreed interface to provide data for external users or require external users to provide data.
========================================================== ====================
Java callback mechanism:
There are always some interfaces between software modules. In terms of calling methods, they can be divided into three types: Synchronous call, callback and asynchronous call.
Synchronous call: a blocking call, which is a one-way call that the caller must wait for the execution of the other party to complete;
Callback: A two-way call mode, that is, the called party also calls the interface of the other party when the interface is called;
Asynchronous call: a mechanism similar to a message or event, but its call direction is the opposite. When an interface service receives a message or an event, the customer is notified (that is, the customer's interface is called ).
Callback and asynchronous call are closely related: callback is used to register asynchronous messages and message notifications are implemented through asynchronous calls.
========================================================== ======================
Example in Java:
Package callbackexample; public interface icallback {// public void postexec ();}
Another class:
Package callbackexample; public class foobar {// composite aggregation principle private icallback callback; Public void setcallback (icallback callback) {This. callback = callback; dosomething ();} public void dosomething () {callback. postexec ();}}
The second class is an anonymous class in the test class:
Package callbackexample; public class test {public static void main (string [] ARGs) {foobar Foo = new foobar (); Foo. setcallback (New icallback () {public void postexec () {system. out. println ("implemented in the test class but cannot be referenced by the test object, but called by the foobar object ");}});}}
Appeal code:
1. Two classes: Anonymous class and foobar
2. Implement interface icallback for anonymous classes (implemented in the form of anonymous classes in the main method of test)
3. foobar has a function setcallback (icallback O) with the icallback interface parameter)
4. Call the setcallback function in foobar when the Anonymous class is running, and pass in parameters as needed.
5. If foobar has obtained an anonymous class, you can call back the methods in the icallback interface implemented in the anonymous class at any time.
========================================
1. First, the concept of callback method is different from that of "Constructor method". It does not refer to a method with special meaning or usage in Java.
2. It is more appropriate to call the "Callback" of a method. It refers to a method call method. Any method called "Callback" can be called a "Callback method"
3. The method callback usually occurs when "Java interface" and "abstract class" are used.
Suppose there is an interface named icallback, and there is a method named postexec ()
Some class myclass has implemented this interface, that is, it must have implemented the postexec () method. Now there is another class foobar which has a method setcallback (icallback callback), and The setcallback method calls the callback postexec () method.
If we use a myclass instance, myclass, and bring it as a parameter to the setcallback (icallback callback) method, we will say setcallback (icallback callback) the postexec () method of myclass is called back.
========================================================== ============================
========================================================== ======================================
The trick is to define a simple interface and declare the method we want to call in this interface.
The following is an example:
Suppose we want to be notified when an event occurs. We can define an interface:
/*
* Get a notification when an event occurs.
*/
Public interface interestingevent {
Public void interestingevent ();
}
Methods In this interface are non-return values and have no parameters. If you want to, you can return values or include parameters. This depends on the specific requirements.
This allows us to control any object of the class that implements this interface. Therefore, we do not need to care about any external type information. This method is much better than using the data fields of the widget to accommodate uncontrollable c Functions of object pointers when using C ++ code for motif.
The code for implementing the interface is as follows:
Public class callme implements interestingevent {
Public callme (){
}
Public void interestingevent (){
System. Out. println ("A printing event occurred, haha ");
}
}
Public class callyou implements interestingevent {
Public callyou (){
}
Public void interestingevent (){
System. Out. println ("A Query event occurred, haha ");
}
}
The class that sends the event signal must wait for the object that implements the interestingevent interface and call the interestingevent () method as appropriate.
Public class eventnotifier {
Private interestingevent ie;
Private Boolean somethinghappened;
Public eventnotifier (){
Somethinghappened = true;
}
Public void setinterestingevent (interestingevent IE ){
This. Ie = ie;
}
Public void dowork (){
If (somethinghappened ){
Ie. interestingevent ();
}
}
}
The following is a test.
Public class test {
/**
* @ Param ARGs
*/
Public static void main (string [] ARGs ){
Callme CM = new callme ();
Callyou Cy = new callyou ();
Eventnotifier en = new eventnotifier ();
En. setinterestingevent (CM );
En. dowork ();
En. setinterestingevent (CY );
En. dowork ();
}
}
In this test, when a specified Calme event is called, The commands under callme are scanned. In the case of a callyou event, the commands under callyou are called. this method can be combined with the command mode. implement the event-driven programming model of MS-windows and X Window System.