在实现中使用数据库时,观察者模式和pub-sub是否相同? [英] Is Observer pattern and pub-sub same when a database is used in the implementation?

查看:101
本文介绍了在实现中使用数据库时,观察者模式和pub-sub是否相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解观察者模式,并停留在某一特定点.以我的理解,一旦观察者订阅了任何事件更改以通知他们,则该订阅存储在某个地方,然后在事件更改时通知订阅者.

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.

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

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.

再一次,发布者/订阅者模式也类似,不同之处在于没有确切的了解发布者和订阅者是谁,并且使用诸如MQ之类的中间技术或某种技术来建立两者之间的通信.

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.

我的问题是:当我们以观察者模式使用DB时,它将不会成为发布者/订阅者(除非这里有观察者和发布者的知识).是正确的理解吗?

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?

推荐答案

在大多数观察者模式示例中,您会看到使用列表,但是如何初始化该列表取决于您的应用程序.例如,具有大量订阅者的应用程序出于持久性原因而必须存储这些订阅者,就像您的情况一样.我们不能指望这么多的订户一直都在内存中.因此,观察者列表仅从数据库中初始化,尽管并非一次性完成所有条目.这是完全不同的讨论.

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.

第二,仅通过使用DB,观察者模式和pub-sub模式就不会变得相似.即使使用DB,您也只需初始化要通知的观察者列表.在它们之间没有中间人可以保留主题的身份并使观察者对Subject类保持隐藏.这是一篇很好的文章,很好地解释了它: https://hackernoon.com/observer-vs-pub-sub-pattern- 50d3b27f838c

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

这篇关于在实现中使用数据库时,观察者模式和pub-sub是否相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆