Search code examples
restdesign-patternsobserver-patternstateless

observer design pattern in rest aplications


I'm trying to learn design patterns, and I have come with the Observer pattern. I think I understand the concept itself, but I don't see when to use it.

I try to explain myself. I work mostly with web applications, so, stateless applications. Normally, the client makes a petition from the browser (for example, update a record). then the operation is completed.

Let us suppose that I want to notify some persons every time a record is updated. It seems to me the perfect scenario for the Observer patter, but when I think of it, it will end something like:

  • user makes petition of update.
  • get all the persons that have to be notified.
  • put all the persons that have to be notified in the observer.
  • make the update. (that also will make the notification for the observer pattern).

but... doing it this way, I have to iterate all the persons that I want to notify twice!

And because its a stateless application, I have to go and get all the persons than needs to be notified every time!

I don't know if the observer pattern is more useful for other types of applications, but I can only think of this pattern in a static form, I mean, making the Observer static.

I know I'm losing something, it's a common and accepted pattern, everyone accept it as a valid solution for this concrete problem. What I am not understanding?


Solution

  • First, let's straighten out the terminology.

    • Each person who wants to be notified is an Observer.
    • Each type of event which can trigger a notification is an Observable.

    Each Observer (person) needs to register itself with the server. It sends a request essentially saying, "I'm interested in foo Observables," which in this case would be, "I'm interested in update events." The server maintains mappings of who is interested in which events.

    Every time the server makes an update, it iterates over the mapping of update Observers and sends a notification to each of them.

    The advantage is that the server and its Observables have no compile-time knowledge of who the Observers are. Observers are free to register (and unregister) themselves at runtime for any event(s) they are interested in.