0 votes
by (2.5k points)
I came across the "Observer" pattern recently, and in reading it, it seems very close to a pub/sub model. You basically have a publisher "notifying" subscribers, except that in the Observer pattern, you have Observers waiting to be notified on an observable/element. So what's the main difference between the two patterns?

1 Answer

0 votes
by (2.5k points)

You're right in that both patterns have a sort of "broadcast an update" type mechanic. And at times, I would say that the observer pattern is almost an example of a pub/sub (But maybe not the other way around). The main differences in my mind are : 

  • The Observer pattern is specifically about OOP programming. The Observers and the Observable are both in the same app, same memory space, basically in the same code space. Whereas Pub/Sub can be two totally different code bases running with some sort of broker in the middle (Like a message queue). 
  • On that same point, Pub/Sub generally has some sort of broker in the middle that the publisher and subscribers both talk to. The subscribers themselves may know nothing about the publisher at all, they only talk to the broker. In the Observer pattern, generally there is some tight coupling with direct references between Observers/Observables
  • Pub/Sub is generally an async mechanic. Because a publisher can be publishing a message on a broker and then not caring about a response or what happens after that. Observables however usually notify synchronously, or at the very least, know who/what they are notifying. 
  • On that note again, Pub/Sub generally has a scalable mechanic where subscribers can scale up or down to meet load and demand. Observers aren't, and again that's because they are often in the same memory space and have direct references to each other. 

Hopefully that answers it. In general, remember that the Observer pattern is specifically an OOP pattern to be implemented in your own code. Whereas pub/sub is a design pattern that could span many code bases, languages, and network topologies. 

Welcome to .NET Q&A, where you can ask questions and receive answers from other members of the community.
...