Applied Design Patterns with Java
Behavioral :: Observer (293) {C ch 22}
Intent
Define a one-to-many dependency between objects so that when
one object changes state, all its dependents are notified and updated automatically.
As Known As
Dependents, Publish-Subscribe
Motivation
A common side-effect of partitioning a system into
a collection of cooperating classes is the need to maintain consistency between related objects. It is not desirable
to achieve consistency by making the classes tightly coupled, as it reduces their reusability. Many GUI
toolkits separate the presentational aspects of the user interface from the underlying application data. Classes
defining application data and presentations can be reused independently. They can work together, too. Both a spreadsheet
object and bar chart object can depict information in the same application data object using different presentations.
The spreadsheet
and the bar chart don't know about each other, allowing reuse only of the one needed. But they behave as
though they do. When the user changes the information in the spreadsheet, the bar chart reflects the changes immediately,
and vice versa.
This behavior implies that the spreadsheet and bar chart are dependent on the data object and therefore should be notified of any change in its state. There's no reason to limit the number of dependent objects to just two; there may be many different user interfaces to the same data. The Observer pattern describes how to establish these relationships. The key objects in this pattern are Subject and Observer. A Subject may have any number of dependent Observers. All Observers are notified whenever the Subject undergoes a change in state. In response, each Observer will query the Subject to synchronize its state with the Subject's state.
This kind of interaction is also known as Publish-Subscribe. The Subject is the publisher of notifications. It sends out these notifications without having
to know who its Observers are. Any number of Observers can subscribe to receive notifications.