Go语言中的观察者模式 [英] Observer pattern in Go language
本文介绍了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.
感谢
推荐答案
这在Go中实际上很简单。使用频道。
This is actually pretty simple in Go. Use channels. This is the kind of thing they're made for.
type Publish struct {
listeners []chan *Msg
}
type Subscriber struct {
Channel chan *Msg
}
func (p *Publisher) Sub(c chan *Msg) {
p.appendListener(c)
}
func (p *Publisher) Pub(m *Msg) {
for _, c := range p.listeners {
c <- Msg
}
}
func (s *Subscriber) ListenOnChannel() {
for {
data := <-s.Channel
//Process data
}
}
func main() {
for _, v := range subscribers {
p.Sub(v.Channel)
go v.ListenOnChannel()
}
//Some kind of wait here
}
显然,这不是一个工作代码示例。但它很接近。
Obviously this isn't exactly a working code sample. But it's close.
这篇关于Go语言中的观察者模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文