Personal Blog

Personal Blog

Observer Design Pattern

Observer Design Pattern

Pub-Sub pattern

Subscribe to my newsletter and never miss my upcoming articles

Observer design patterns can be an architectural solution to several behavior problems that appear in software architecture or development. The pattern is applicable to the following cases:

  1. When a change to one object requires the change or update in another object while we do not know how many objects need to be changed.

  2. When an object should be able to notify other objects without assuming who those objects are.

Imagine the situation where we have a post office (subject) and people (observers) who expect to receive mails. In order to check whether they have mails, they have to infinitely check post office mailbox, which is really bad. Or another example of website development, we have two views that depend on one model, the views, in order to check the state of the model to update themselves, have to check the model state infinitely or in some time interval which is a time consuming and a very expensive process.

Observer pattern solves the issue “push vs pull”. The pattern enables the situation that the views (observers) in our example, rather than pulling the information from the model, the model (subject) notifies the views about the change. For the second example, the people, instead of checking the mailbox infinitely, the post office will notify the people (observers) about the mails and relevant observers will get the mail that belongs to them.

The java implementation of the following example (MailOffice and People) is given in my github repository

 
Share this