Realize the callback routine with Java

zhaozj2021-02-16  60

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 interestingEvent ();} 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. This method is much better than that compared to the difficult C function of the object pointer. 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 SomettingHappened 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-16211.html

New Post(0)