Home  >  Article  >  Backend Development  >  How to Implement the Observer Pattern in Go Using Channels?

How to Implement the Observer Pattern in Go Using Channels?

Barbara Streisand
Barbara StreisandOriginal
2024-11-05 12:59:02263browse

How to Implement the Observer Pattern in Go Using Channels?

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!

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