Definition: define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically
Based on design principle: strive for loosely coupled designs between objects that interact
The subject and observers define the one-to-many relationship. One subject notifies many observers when subject state changes. Subjects update Observers using a common interface. Observers of any concrete type can participate in the pattern as long as they implement the Observer interface.
The Observer Pattern is a perfect example of “loose coupling”:
- subject knows nothing about observers, only that they implement the Observer interface
- very easy to add new observers without need to modify the subject
- subjects or observers can be reused independently of each other
- changes to subject or an observer will not affect the other
How it works:
ConcreteSubject notifies its observers whenever a change occurs by calling subscribed (added to the subjects list) observer objects update() methods. After being informed of a change in the ConcreteSubject, a ConcreteObserver objects may query the subject for information. There are two ways of data retrieval from ConcreteSubject. It could be pushed through update() method as parameter, or update() method could call ConcreteSubject method getState() and pull data from it. Data pull is considered a more flexible option.