Observer Pattern in Go Language
In software engineering, the Observer pattern is employed when it's necessary to notify a collection of subscribers when an event occurs within an object. A common framework for achieving this in C is boost::signals. This question explores how to replicate this functionality in Go, using an example that demonstrates how multiple subscribers can register with a publisher and receive notifications.
Solution
The Observer pattern can be easily implemented in Go using channels. Their inherent purpose is to facilitate the communication between concurrent goroutines.
type Publisher 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 }
While this example is not a complete working code sample, it provides a solid foundation for implementing the Observer pattern in Go using channels.
The above is the detailed content of How to Implement the Observer Pattern in Go Using Channels?. For more information, please follow other related articles on the PHP Chinese website!