简体   繁体   English

在实现中使用数据库时,观察者模式和pub-sub是否相同?

[英]Is Observer pattern and pub-sub same when a database is used in the implementation?

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. 在实际情况下,出于持久性原因,我应该将值存储在数据库或文件中,并在事件发生时通过从db获取并遍历列表来通知它们。

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. 再者,发布者/订阅者模式也类似,不同之处在于没有确切的了解发布者和订阅者是谁,并且使用MQ之类的中间技术或某种技术来建立两者之间的通信。

My question is : When we use DB in observer pattern wont it become publisher/subscriber ( except there is knowledge of observers and publishers here). 我的问题是:当我们以观察者模式使用DB时,它不会成为发布者/订阅者(除非这里有观察者和发布者的知识)。 Is it correct understanding? 是正确的理解吗?

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. 其次,仅通过使用DB,观察者模式和pub-sub模式就不会变得相似。 Even using DB, you are simply initializing your list of observers which are to be notified. 即使使用DB,您也只是在初始化要通知的观察者列表。 There is no broker in between which would keep identities of subject and keep observer hidden from the Subject class. 在它们之间没有中间人可以保留主题的身份并使观察者对Subject类保持隐藏。 Here is good article that explains it nicely: https://hackernoon.com/observer-vs-pub-sub-pattern-50d3b27f838c 这是一篇很好的文章,很好地解释了这个问题: https : //hackernoon.com/observer-vs-pub-sub-pattern-50d3b27f838c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM