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
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.
There is also go-observer (https://github.com/imkira/go-observer). They compare observer with channels.
来源:https://stackoverflow.com/questions/3733761/observer-pattern-in-go-language