The Observer design pattern allows the object to manage a number of observers who respond to changes of its state by calling their methods.
Dealing with dependencies is one of the key issues in software design. Very often, several objects can depend on one specific object. E.g. a user instance in a desktop application changes its address, however, all open forms and other dialogs with this name must be notified of this change. Moreover, an external registry service, which is used to send catalogs by mail, should be notified.
From the design point of view, it's not appropriate to pollute the user object with this logic. It shouldn't know about the objects that depend on it because it would make it unnecessarily complicated and unreadable. Thanks to Observer, the user object can be shielded from these objects.
The object being observed is referred to as
Subject in the
pattern. It's an abstract class containing methods for adding, removing and
notifying observers. Observer depends on
Subject. It inherits from
Observer abstract class and therefore implements an interface
that allows it to be notified when the subject changes. Subject manages a
collection of its observers at the abstract level.
When the state changes, the subject calls its
and doesn't care about anything else. This method is implemented in the
Subject abstract class and iterates over the collection of its
update() method is called on them, which makes their
state consistent again.
The pattern is used in systems based on event processing.