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

DDD
Release: 2024-11-05 11:01:02
Original
985 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!