Java Reference
In-Depth Information
Observable and Observer Objects
The class Observable provides you with an interesting mechanism for communicating a change in one
class object to a number of other class objects. One use for this mechanism is in GUI programming where
you often have one object representing all the data for the application - a text document, for instance, or a
geometric model of a physical object- and several other objects that represent views of the data that are
displayed in separate windows, where each shows a different representation or perhaps a subset of the data.
This is referred to as the document/view architecture for an application, or sometimes the model/view
architecture . This is a contraction of something referred to as the model/view/controller architecture and we
will come back to this when we discuss creating Graphical User Interfaces ( GUI ). The document/view
terminology is applied to any collection of application data - geometry, bitmaps, or whatever. It isn't
restricted to what is normally understood by the term 'document'.
Document
A Document object
contains all the
application data
A Document object needs to tell its Views when changes occur
View
View
View
View objects display aspects of the Document data. Views are
usually owned by the Document object.
When the Document object changes, all the views need to be notified that a change has occurred, since they
may well need to update what they display. The document is observable and all the views are observers . This
is exactly what the Observable class is designed to achieve, when used in combination with an interface,
Observer . A document can be considered to be an Observable object, and a view can be thought of as an
Observer object. This enables the view to respond to changes in the document.
The document/view architecture portrays a many-to-many relationship. A document may have many
observers, and a view may observe many documents.
Defining Classes of Observable Objects
You use the Observable class in the definition of a class of objects that may be observed. You simply
derive the class for objects to be monitored, Document say, from the class Observable .
Any class that may need to be notified when a Document object has been changed must implement the
interface Observer . This doesn't in itself cause the Observer objects to be notified when a change in
an observed object occurs; it just establishes the potential for this to happen. You need to do something
else to link the observers to the observable, which we'll come to in a moment.
Search WWH ::




Custom Search