Java Reference
In-Depth Information
Sidebar 8.1 Observer
observable
Java provides the
java.util.Observable
class and the
java.util.Observer
interface for implementing the
event notification mechanism. The
Observable
is the broadcaster object that provides information
to a set of listener objects (
Observers
). The underlying architectural model is known as
Model
-
View
-
Controller and has been documented as pattern
Observer
.
Class
Observable
offers method
notifyObservers()
to inform observer objects that some data have
changed. When this occurs, observers update their state to reflect the new data. State transitions
are defined in the
update()
method that every subclass of interface
Observer
must implement.
The call to
notifyObservers()
results in a call to the
update()
method of each
Observer
. This means
that the
Observable
object remains blocked until all of the
Observer
objects have completed the exe-
cution of their
update()
methods.
The code below implements an example, where the
Equipment
class plays the role of the
observable that changes state at random time instants. Class
Controller
plays the role of the observer
that is notified of the observable's state changes. Class
Monitor
initializes the communication
between
Equipmet
and
Controller
by adding
Controller
in the
Equipment
's list of observer objects.
import
java.util.*;
public class
Equipment
extends
Observable
implements
Runnable {
int
counter
#
0;
public void
run() {
while
(
true
) {
try
{
System.out.println("Equipment: state change :
"
!
(
!!
counter));
this
.setChanged();
this
.notifyObservers(
new
Integer(counter));
Thread.sleep(Math.round(Math.random()*2000.0
!
500.0));
}
catch
(InterruptedException i.e.) {}
}
}
}
public class
Controller
implements
Observer{
public void
update(Observable observable, Object object) {
Integer value
#
(Integer) object;
if
(Math.IEEEremainder(value.intValue(), 2.0)
##
0.0)
System.out.println("Even value "
!
value.intValue());
else
System.out.println("Odd value "
!
value.intValue());
}
}
public class
Monitor {
public static void
main(String[] args) {
Equipment equipment
#
new
Equipment();
Controller controller
#
new
Controller();
equipment.addObserver(controller);
Thread thread
#
new
Thread(equipment);
thread.start();
}
}