觀察者模式涉及一個發布者對象,在發生特定事件時通知其訂閱的觀察者。 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中文網其他相關文章!