Reuse java.util.observable classes

zhaozj2021-02-16  56

Usually you can fully develop your own Listener / Event (listener / event) system, but there is already an existing universal solution in the Java standard library, which can save a lot of time.

In the Java library, the use of events and listeners is very common, which are just examples of the Observer mode. An Observable / Observer pair is provided in the Java UITL package, although it is not very powerful, but it is still useful under many occasions.

The following three classes demonstrate a way using 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 ("Changd.");} 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 need to pay attention is that the OEVENT class stores the event message in the source. Typically, this should be stored as an object of an excitation event, and an event message should also be stored in a separate domain, but this is made up of a simple purpose. Another need to pay attention to the use of OBSERVABLE's setchanged method, if OBSERVABLE does not change, it does not notify the observer; instead, it simply ignores the call to the NotifyObservers method. Here is the output of the sample program: 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 enforces the Update (Observable, Object) method signature (SIGNATUR),

So the OBSERVER / OBSERVABLE class does not replace your own defined Event / Listener class; when the interface is acceptable,

They are a useful tool.

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

New Post(0)