Generally, you can develop a complete set of Listener/Event (Listener/Event) systems, but the existing general solutions are available in the Java standard library, it can save a lot of time.
In the Java library, the use of events and listeners is common. These are only examples of the Observer (Observer) mode. The Java Uitl package provides an Observable/Observer pair. Although it is not very powerful, it is still useful in many cases.
The following three classes demonstrate how to use the Observer/Observable class.
Import java. util .*;
Public class OEventManager extends Observable {
Static public void main (String [] args ){
OEventManager mgr = new OEventManager ();
Mgr. addObserver (new OListener ());
Mgr. addObserver (new OListener ());
Mgr. addObserver (new OListener ());
Mgr. fireChange ("Changed .");
}
Public void fireChange (String msg ){
SetChanged ();
NotifyObservers (new OEvent (msg ));
}
}
Class OListener implements Observer {
Public void update (Observable o, Object arg ){
System. err. println ("Passed" + arg + "by" + o + "to" + this );
}
}
Class OEvent extends EventObject {
Public OEvent (String msg ){
Super (msg );
}
}
One important thing to note is that the OEvent class stores event messages in the source. In general, the object that inspires the event should be stored here, and the event message should also be stored in a separate domain, but this is for a concise purpose.
Another thing to note is the use of the setChanged method of the Observable. If the Observable does not change, it does not notify the observer. On the contrary, it simply ignores calls to the yyobservers method.
The output of the example program is as follows:
Passed OEvent [source = Changed.] by OEventManager @ c9a to OListener @ 3b63e6
Passed OEvent [source = Changed.] by OEventManager @ c9a to OListener @ 25cf3e
Passed OEvent [source = Changed.] by OEventManager @ c9a to OListener @ 48f0cd
Because the Observer interface forces the update (Observable, Object) method signature (signature), the Observer/Observable class cannot replace your own defined Event/Listener class; they are a useful tool when this interface is acceptable.