Observer Design Pattern

Observer Design Pattern

Design Patterns Serie

Intent

It is used when there is a one-to-many relationship between objects. So, if one object is modified, its dependent objects will be automatically notified.

Problem

Imagine that we have an electronics store, and there will be a new phone coming soon to that store. Some people are interested in buying it so they come to the store every day to ask whether it is available now or not.
Do you think this is an efficient way to know? Absolutely Not!
As customers will put much pointless effort every day in their walk to the store. At the same time, the store can't send emails to all the customers to notify them when the phone is available because this would make the uninterested customers think that it is spam mail. So, what should we do?

Solution

We can make the interested customers subscribe to the mail service of the store, and choose to be notified when the phone is available at the store. The object that has some interesting state is often called "subject," (the store here in our case).
All other objects that want to track changes to the subject's (store’s) state are called "subscribers".

Pros and Cons

Pros

  • We can establish relations between objects at runtime.
  • We can introduce a new subscriber (customer) class without making a change in the subject's (store's / publisher's) code.

Cons

  • Subscribers are notified in random order.
  • Not implementing it carefully, will lead to a large complexity in the code.

Thank you, and goodbye.