问题
I am trying to understand observer pattern and stuck at one particular point. In my understanding, once an observer subscribes to notify them on any event change, the subscription is stored somewhere and then when event changes the subscriber is notified.
In practical scenarios I should store the values in a database or a file for persistence reasons and inform them once event occurs by getting from db and looping through the list.
Is this correct understanding? I do not see any example involving database but, every example uses list.
And again publisher/subscriber pattern is also similar except with the change that there is no exact knowledge of who the publisher and subscribers are and intermediate technologies like MQ or some sort is used to establish communication between two.
My question is : When we use DB in observer pattern wont it become publisher/subscriber ( except there is knowledge of observers and publishers here). Is it correct understanding?
回答1:
In most examples for Observer pattern you would see use lists but how that list is initialized depends on your application. For example, application with huge number of subscribers would have to store these subscribers for persistence reasons just like your case. We can't expect such high number of subscribers to be in memory all the time. So the list of observers is initialized from DBs only although not all entries in one go. This is a different discussion altogether.
Secondly, simply by using DB, observer pattern and pub-sub pattern don't become similar. Even using DB, you are simply initializing your list of observers which are to be notified. There is no broker in between which would keep identities of subject and keep observer hidden from the Subject class. Here is good article that explains it nicely: https://hackernoon.com/observer-vs-pub-sub-pattern-50d3b27f838c
来源:https://stackoverflow.com/questions/47767121/is-observer-pattern-and-pub-sub-same-when-a-database-is-used-in-the-implementati