Java Reference
In-Depth Information
responsibility is to transmit events to any interested observers; that is, any observers that are registered with the
observable component. A listener interface allows the observable component to indicate what events have
occurred and possibly to provide details to observers.
You can think of the Observer pattern as a server-push solution. The server (in this case, the observable object or
event producer) contacts the interested listeners when there is a new event of some kind.
The Observer pattern is useful for a variety of applications. Notifications are only broadcast to elements who
identify themselves as interested receivers. This allows the receivers to respond in whatever way is meaningful to
them. This is well-suited for any model where changes in one component might result in changes to others, and
where the behavior might be configurable during runtime.
In business models, Observer can be helpful when a model exhibits complex update, delete, or refresh behavior.
The flexible nature of the pattern makes it possible for a change in a business element to be broadcast to some or
all other elements in the model.
Activity in the Observer pattern is comparable to what happens during dating. A single person (the observable)
has one or more friends (observers) who have said they are interested in knowing how the dates go, and so they
become registered listeners. As new events (dates of varying quality and success) take place in the single's life, he
or she broadcasts messages to friends, providing them with details about dating experiences. The friends respond
to the messages, with suggestions, congratulations, sympathy, or shock as appropriate.
Implementation
The Observable class diagram is shown in Figure 2.10 .
Figure 2.10. Observable class diagram
The Observable pattern includes the following:
Observable - The interface that defines how the observers/clients can interact with an Observable . These
methods include adding and removing observers, and one or more notification methods to send information
through the Observable to its clients.
ConcreteObservable - A class that provides implementations for each of the methods in the Observable
interface. It needs to maintain a collection of Observers .
The notification methods copy (or clone) the Observer list and iterate through the list, and call the specific
listener methods on each Observer .
Observer - The interface the Observer uses to communicate with the clients.
 
Search WWH ::




Custom Search