The OBServer interface and the OBServable class can be used in Model-View mode: When the data in the model changes, the Model actively informs the VIEW. The MODEL is implemented with the OBServable class, and the view can be implemented with a class that implements the OBSERVER interface. For example, as follows:
Import java.util. *;
Public Class MyModel Extends Observable {Private String Data;
Public void change (STRING SVALUE) {data = svalue; system.out.println ("Changing to" svalue "..."); setChanged ();}}
MyModel is an OBSERVABLE class that can be packaged in data DATA. When Data changes, it actively calls the parent class OBSERVABLE's setChanged () method.
Import java.util. *;
Public class testobserver {public static void main (string [] args) {mymodel model = new mymodel (); model.addobserver (new observer () {// Registered anonymous internal class OBSERVER: When data changes Class Update method public void update (Observable O, Object Arg) {system.out.println ("The value has been change to" (string) arg);}}); String Svalue = "Observer test"; model. Changevalue (Svalue); // Change Data Model.NotifyObservers (Svalue "!"); // Data Changes You need to actively notify each OBServer by Model, which is the OBServer's Update method will be called.
}
}
This mode is required to actively notify the View generating events.
Another better way is: 1. Define event classes (subclats for EventObject); 2. Define listeners (inherited EventListener interfaces, and define event processing methods. Note: Definition, not implementation); 3, give one Class myclass increases the implementation code that events occurred in registration events and notification events. 4. When using the MyClass class, register the event listener and instantiate the method in this listener interface. This allows the method implemented in the listener when the event occurs.