Search⌘ K

Observer Pattern

Explore the Observer Pattern to understand how objects can subscribe to and receive updates from other objects in a one-to-many relationship. Learn how this pattern supports loose coupling and flexibility in software design through real-world examples like air traffic control systems and social media models.

What is it ?

Social media helps us immensely in understanding the observer pattern. If you are registered on Twitter then whenever you follow someone, you are essentially asking Twitter to send you (the observer) tweet updates of the person (the subject) you followed. The pattern consists of two actors, the observer who is interested in the updates and the subject who generates the updates.

A subject can have many observers and is a one to many relationship. However, an observer is free to subscribe to updates from other subjects too. You can subscribe to news feed from a Facebook page, which would be the subject and whenever the page has a new post, the subscriber would see the new post.

The pattern is formally defined as a one to many dependency between objects so that when one object changes state all the dependents are notified.

Class Diagram

The class diagram consists of the following entities:

  • Subject
  • Observer
  • Concrete Subject
  • Concrete Observer

The class diagram in general is shown below.

widget

To ensure loose coupling we'll define an interface ...