What is the Observer Design Pattern?
The Observer design pattern deals with the problem of
how an "observable object" can notify several independent
and loosely coupled "observer objects" that it has changed,
so that they may update themselves accordingly.
Here is the basic formulation of the Observer design pattern:
-
Name
The name of the design pattern is Observer.
-
Intent
The intent of this design pattern is to provide a loose
coupling between an observable subject and one or more
observers. A subject notifies it observers whenever its
(the subject's) state changes. When notified by the subject,
the observers also change in response to the change in the
subject.
-
Solution
In Java, in the java.util package, there is an Observable
class and an Observer interface that permit a programmer
to set up "observables" and "observers" that respond to
changes in them.
-
Consequences (quoted from Java Design Patterns,
by James Cooper)
-
The Observer pattern promotes abstract coupling to Subjects.
A subject doesn't know the details of any of its Observers.
This has the potential disadvantage of successive or repeated
updates to the Observers when there is a series of incremental
changes to the data. If the cost of these updates is high,
introducing some sort of change management might be necessary
so that the Observers are not notified too soon or too often.
-
When one client changes the underlying data, you need to
decide which object will initiate the notification of the
change to the other Observers. If the Subject notifies all
of the Observers when it is changed, each client is not
responsible for remembering to initiate the notification.
However, this can result in a number of small successive
updates being triggered. If the clients tell the Subject
when to notify the other clients, this cascading notification
can be avoided; however, the clients are left with the
responsibility to tell the Subject when to send the notifications.
If one client "forgets", the program simply won't work properly.
-
Finally, you can specify the kind of notification to send
by defining a number of update methods for the
Observers to receive, depending on the type or scope of
change. In some cases, the clients will thus be able to
ignore some of these notifications.
List of All Topics