The Observer design pattern solves problems like:
How can a one-to-many dependency between objects be defined
without making the objects tightly coupled?
How can an object notify an open-ended number of
other objects?
See Applicability section for all problems Observer can solve.
See Solution section for how Observer solves the problems.
-
An inflexible way to define a one-to-many dependency
between objects
is to define
one object
(
Subject1)
that implements updating the state of
dependent objects
(Dependent1,Dependent2,…).
That means, subject must know how to update
the state of many different objects (having different
interfaces).
-
This commits (tightly couples) the subject to particular dependent objects
and makes it impossible to change the objects (add new ones
or remove existing ones) independently from
(without having to change) the subject. It stops the subject from being reusable
and makes the subject hard to test.
Tightly coupled objects
are hard to implement, change, test, and reuse
because they depend on
(refer to and know about)
many different objects.
"You don't want to achieve
consistency by making the classes tightly coupled,
because that reduces their reusability."
[GoF, p293]
-
That's the kind of approach to avoid if we want
to keep the objects in a one-to-many dependency loosely coupled.
-
For example, a data object and multiple
presentation objects in a GUI/Web
application.
When the data object changes state, all presentation
objects that depend on this data object's state should be
updated (synchronized) automatically and immediately
to reflect the data change
(see Sample Code /
Example 2).
-
For example, event handing in a GUI/Web application.
When a user clicks a button, all
objects that depend on (listen for) the button's
'click event'
should be notified that a 'click event' occurred
(see Sample Code /
Example 3/4).