Skip to content

Instantly share code, notes, and snippets.

@nbari
Last active January 19, 2016 15:21
Show Gist options
  • Save nbari/acd7c5c695624a290151 to your computer and use it in GitHub Desktop.
Save nbari/acd7c5c695624a290151 to your computer and use it in GitHub Desktop.
observer pattern in go
package main
import (
"fmt"
"sync"
"time"
)
type Producer struct {
chs []chan<- int
}
func (p *Producer) Register(ls ...*Listener) {
for _, l := range ls {
p.chs = append(p.chs, l.ch)
}
}
func (p *Producer) Fanout(i int) {
for _, ch := range p.chs {
ch := ch
go func(i int) {
ch <- i
}(i)
}
}
type Listener struct {
ch chan int
}
func (l *Listener) Listen(prefix string, wg *sync.WaitGroup) {
go func(p string, w *sync.WaitGroup) {
for i := range l.ch {
time.Sleep(1 * time.Second)
fmt.Println(p, i)
w.Done()
}
}(prefix, wg)
}
func main() {
var wg sync.WaitGroup
l1 := &Listener{make(chan int, 0)}
l1.Listen("listener 1:", &wg)
l2 := &Listener{make(chan int, 0)}
l2.Listen("listener 2:", &wg)
p := &Producer{make([]chan<- int, 0)}
wg.Add(2)
p.Register(l1, l2)
p.Fanout(5)
wg.Wait()
fmt.Println("exit")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment