Go语言中的观察者模式
这个问题很常见:当某个事件发生时,一个对象应该通知它的所有订阅者。在 C++ 中,我们可以使用 boost::signals 或其他东西。但是用 Go 语言如何做到这一点呢?很高兴看到一些工作代码示例,其中几个对象订阅了发布者并处理通知。
谢谢
This problem is pretty common: an object should notify all its subscribers when some event occurs. In C++ we may use boost::signals
or something else. But how to do this in Go language? It would be nice to see some working code example where a couple of objects are subscribed to a publisher and process notifications.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这在 Go 中实际上非常简单。使用渠道。这就是它们的用途。
显然这不完全是一个有效的代码示例。但已经很接近了。
This is actually pretty simple in Go. Use channels. This is the kind of thing they're made for.
Obviously this isn't exactly a working code sample. But it's close.
这里我给出了一个没有通道的经典实现,请随意参考这个 帖子
假设示例:
假设您对股票市场感兴趣。您有以下需求: 您想要跟踪特定公司(例如 Apple Inc)的股票价格。您不想错过任何股票价格更新,尤其是当价格跌至某个点时。您希望收到所有股票价格更新的通知。
接口:
具体观察者对象
具体主体对象
main.go
在这部分
将它们附加到 stockMonitor。
Here I give a classific implementation without channels, be free to refer this post
Assumed Example:
Suppose you are interested in the stock market. You have the following needs: You want to keep track of the stock prices of a particular company (e.g. Apple Inc). You would not like to miss any stock price update especially if the price is dropping to a certain point. You would like to be notified of all the stock price updates.
interfaces:
Concrete Observer object
Concrete Subject object
main.go
In this part
Attach them to the stockMonitor.