Good object-oriented design emphasizes both encapsulation
and loose coupling. The Observer Pattern is a mechanism for drastically
reducing coupling between interacting classes. The observer pattern should be
used whenever one or more objects (observers) must track changes in the
subject. In most applications, classes do not work in isolation; they interact
with many other classes. A common scenario of class interaction occurs when
one class (the Observer) needs to be notified when something changes in another
(the Subject).
In this pattern, an observer registers with a subject and
subsequently receives notifications and is usually encountered both in everyday
life and in the software Development applications.
Its intent is to define a one-to-many dependency between
objects so that when one object changes state all its dependents are notified
and updated automatically
This pattern allows us to plug objects into a framework at
runtime, which allows for highly flexible, extensible, and reusable software.
This pattern is also called the Publish-Subscribe pattern.
Observer pattern can be applied in any of the following
situations.
1.
It can be applied when the abstraction has two aspects with one
dependent on the other. Encapsulating these aspects in separate objects will
increase the chance to reuse them independently.
2.
Use it when the subject object does not know exactly how many observer
objects it has.
3.
Or use it when the subject object should be able to notify its observer
objects without knowing who these objects are.
The following Non-software and .NET Framework examples demonstrate
this pattern.