Tuesday, November 27, 2018

PubSub design patterns vs observer pattern


Let’s assume that you are searching for a job as a software engineer and very interested in a company named ‘Banana Inc.’. So, you contacted their Hiring Manager and gave him your contact number. He ensured you that if there is any vacancy they will let you know. And there are several other candidates interested too, like you. They will let all of the candidates know about the vacancy and maybe if you respond then they will conduct an interview. So, how is this scenario related to ‘Observer’ design pattern? Here, the company ‘Banana Inc.’ is the Subject which is maintaining a list of all the Observers (candidates like you) and will notify the observers for a certain event ‘vacancy’. Ain’t it easy, mate?

In ‘Publisher-Subscriber’ pattern, senders of messages, called publishers, do not program the messages to be sent directly to specific receivers, called subscribers.

This means that the publisher and subscriber don’t know about the existence of one another. There is a third component, called broker or message broker or event bus, which is known by both the publisher and subscriber, which filters all incoming messages and distributes them accordingly.

Let’s list out the differences as a quick Summary:
  • In the Observer pattern, the Observers are aware of the Subject, also the Subject maintains a record of the Observers. Whereas, in Publisher/Subscriber, publishers and subscribers don’t need to know each other. They simply communicate with the help of message queues or broker.
  • In Publisher/Subscriber pattern, components are loosely coupled as opposed to Observer pattern.
  • Observer pattern is mostly implemented in a synchronous way, i.e. the Subject calls the appropriate method of all its observers when some event occurs. The Publisher/Subscriber pattern is mostly implemented in an asynchronous way (using message queue).
  • Observer pattern needs to be implemented in a single application address space. On the other hand, the Publisher/Subscriber pattern is more of a cross-application pattern.

https://hackernoon.com/observer-vs-pub-sub-pattern-50d3b27f838c

No comments:

Followers

Link