Java Reference
In-Depth Information
Chapter 9. Observer
Clients ordinarily gather information from an interesting object by calling its methods. But
when an interesting object changes, a problem arises: How do clients that depend on the
object's information know that the information has changed?
You may encounter designs that make an object responsible for informing clients when an
interesting aspect of the object changes. The problem with this is that the knowledge of which
attributes about an object are interesting lies with the client. The interesting object shouldn't
accept responsibility for updating the client.
One solution is to arrange for clients to be informed when the object changes and leave it to
the clients to follow up with interrogations about the object's new state. The intent of the
O BSERVER pattern is to define a one-to-many dependency such that when one object changes
state, all its dependents are notified and updated automatically.
A Classic Example: Observer in Swing
The most common case in which clients depend on changing objects occurs in graphical user
interfaces. Whenever a user clicks a button or adjusts a slider, many objects in the application
may need to react to the change. Java Swing anticipates that you will be interested in knowing
when a user changes a Swing component, and the O BSERVER pattern is evident throughout
Swing. Swing refers to interested clients as "listeners" and lets you register as many listeners
as you like to be notified of a component's events.
Consider a typical Oozinoz application with a Swing GUI, such as the one that Figure 9.1
shows. This application lets a fireworks engineer experiment visually with parameters that
determine the relationship between a rocket's thrust and the surface area of its fuel.
Figure 9.1. The curves shown change in real time as the user adjusts the tPeak variable
with the slider.
When a solid rocket engine ignites, the part of its fuel that is exposed to air burns, producing
thrust. From ignition to maximum burn rate, the burn area increases from the initial ignition
area to the full surface area of the fuel. This maximum rate occurs at time t peak . As fuel burns
off, the surface area reduces again until the fuel is consumed.
Search WWH ::




Custom Search