22.4 JDK support for observer Mode
Observer mode plays an important role in Java. In the JDK java. util package, the observable class and the observer interface are provided, which constitute JDK's support for the observer mode. 22-5:
Figure 22-5 structure of the observable class and observer interface provided by JDK
(1) Observer Interface
Only one method is declared in the Java. util. Observer interface, which acts as an abstract observer. The method declaration code is as follows:
Void Update (observable o, object Arg ); |
When the status of the object changes, this method will be called and the update () method will be implemented in the subclass of the observer, that is, the specific observer can have different update behaviors as needed. When you call the yyobservers () method of the observable object class, the update () method in the Observer class is executed.
(2) observable class
The Java. util. observable class acts as the observation object class and defines a vector in the observable to store the observer object. The methods and descriptions contained in the vector are shown in table 22-1:
Table 22-1 methods and descriptions of the observable class
Method Name |
Method description |
Observable () |
Constructor: instantiate a vector. |
Addobserver (Observer O) |
Registers a new observer object to a vector. |
Deleteobserver (Observer O) |
Deletes an observer object in a vector. |
Yyobservers () and notifyobservers (Object Arg) |
The notification method is used to call the update () method of each observer in the vector cyclically within the method. |
Deleteobservers () |
Deletes all observer objects in a vector. |
Setchanged () |
After this method is called, the changed value of a Boolean internal variable is set to true, indicating that the status of the target object has changed. |
Clearchanged () |
It is used to set the value of the changed variable to false, indicating that the object state is no longer changed or all observer objects are notified, and their update () method is called. |
Haschanged () |
Used to test whether the object status changes. |
Countobservers () |
Returns the number of observers in a vector. |
WeThe observer interface and the observable class can be directly used as the abstract layer of the observer mode, and then the specific observer class and the specific observation target class can be customized.By using the observer interface and the observable class in JDK, you can more easily apply the observer mode in Java.
[Author: Liu Wei http://blog.csdn.net/lovelion]