观察者模式涉及一个发布者对象,在发生特定事件时通知其订阅的观察者。 Go 语言提供了一种使用通道来实现此模式的简单方法。
为了理解其工作原理,让我们考虑多个对象订阅发布者的场景。然后,发布者可以通过通道向所有订阅者广播通知。
下面是演示观察者模式的 Go 示例代码:
package main import "fmt" // Publisher is an object that can notify subscribers of an event. type Publisher struct { listeners []chan string } // Subscriber represents an object that can receive notifications from a Publisher. type Subscriber struct { ID int Channel chan string } // Sub adds a Subscriber to the Publisher's list of listeners. func (p *Publisher) Sub(sub *Subscriber) { p.listeners = append(p.listeners, sub.Channel) } // Pub sends a notification to the Publisher's subscribers. func (p *Publisher) Pub(msg string) { for _, c := range p.listeners { c <- msg } } // Run starts a Subscriber listening for notifications from the Publisher. func (s *Subscriber) Run() { for { msg := <-s.Channel fmt.Printf("Subscriber %d received: %s\n", s.ID, msg) } } func main() { // Initialize Publisher publisher := &Publisher{} // Create and add Subscribers for i := 0; i < 3; i++ { subscriber := &Subscriber{ID: i, Channel: make(chan string)} publisher.Sub(subscriber) go subscriber.Run() } // Send notifications publisher.Pub("Hello 1") publisher.Pub("Hello 2") publisher.Pub("Hello 3") }
在这个示例中,发布者(Publisher)有一个列表广播通知的频道(侦听器)。订阅者(Subscriber)有自己的频道(Channel)来接收通知。当发布者发送通知 (Pub) 时,它会通过其通道将其发送给所有订阅者。然后每个订阅者打印收到的通知。这演示了发布者如何向其观察者广播更新。
以上是Go中如何使用通道来实现观察者模式?的详细内容。更多信息请关注PHP中文网其他相关文章!