Home  >  Article  >  Backend Development  >  How can Go channels be used to implement the Observer Pattern?

How can Go channels be used to implement the Observer Pattern?

DDD
DDDOriginal
2024-11-05 11:01:02988browse

How can Go channels be used to implement the Observer Pattern?

Observer Pattern in Go Language

In many programming scenarios, a need arises where an object must notify multiple subscribers upon an event's occurrence. This pattern is typically known as the Observer Pattern. In Go, channels provide an elegant solution for implementing this pattern.

The code sample below demonstrates a working example:

<code class="go">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() {
    publisher := &Publisher{}

    subscribers := []*Subscriber{
        &Subscriber{make(chan *Msg)},
        &Subscriber{make(chan *Msg)},
        // Additional subscribers can be added here
    }

    for _, sub := range subscribers {
        publisher.Sub(sub.Channel)
        go sub.ListenOnChannel()
    }

    publisher.Pub(&Msg{"Event Notification"})

    // Pause the main function to allow subscribers to process messages
    time.Sleep(time.Second)
}

type Msg struct {
    Message string
}</code>

In this example, the Publisher holds a slice of listener channels, which represent the subscribed objects. The Pub method notifies all listeners by sending data to their channels. Each Subscriber listens continuously on its dedicated channel for incoming data to process.

The above is the detailed content of How can Go channels be used to implement the Observer Pattern?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn