Realize the callback routine with Java

zhaozj2021-02-08  301

Author: John D. Mitchell

Summary

Before the Java support method pointer, the Java interface does not provide a good way to achieve callbacks. If you are accustomed to passing a function pointer called in an event-driven programming model, you will like this skill.

Familiar with the MS-Windows and X Window System event-driven programming model developers who are accustomed to passing the function pointer that calls (ie, "callback") when a certain event occurs. Object-oriented models of Java currently does not support method pointers, which seems to use this good mechanism. But we are not a little way!

Java's interface support provides a mechanism for obtaining an equivalent function of a callback. Its skill is: Define a simple interface and declare the way we want to call in this interface.

For example, suppose we want to get notifications when an event occurs. We can define an interface:

Public interface interestingEvent {// This is just a general method. So if necessary, // which can have a return value, or receive parameters. Public void interstingevent ();

This allows us to control any objects of the class that implements the interface. Therefore, we don't have to care about any external type information. This method should be much better than the data domain that uses the widget when using the C code for MotiF.

The class that issues an event signal must wait for the object of the InterestingEvent interface and call the interessingEvent () method at the appropriate time.

Public Class EventNotifier {Private InterestNGEvent IE; Private Boolean SomethingHappend; Public EventNotifier (INTERESTINGEVENT EVENT) {// Save the event object after standing. IE = Event; // There is no event to report. Somethinghapped = false;} // ... public void dowork () {// check the predicate set at elsewhere. If (SomethingHappend) {// The event signal is issued by calling this method of the interface. IE.INTERESTINGEVENT ();} // ...} // ...}

In the above example, I use the SomethinghapPpened predicate to track whether the event should be triggered. In many cases, call this method is enough to ensure signals to InterestingEvent ().

The code that wants to receive event notifications must implement the InterestingEvent interface and passed your own reference to the event notification program.

Public Class Callme Implements InterestingEvent {Private EventNotifier En; Public Callme () {// Create Event Notification Program and passes your own reference to it. EN = New EventNotifier (this); // Define the actual handler for events. Public void interestingEvent () {// 噢! I must have an incident that is interested in! // Execute some operations ...} // ...}

转载请注明原文地址:https://www.9cbs.com/read-950.html

New Post(0)