package observer import ( "sync" "time" "github.com/pingcap/log" ) type Event struct { Data int } type Observer interface { NotifyCallback(event Event) } type Subject interface { AddListener(observer Observer) RemoveListener(observer Observer) Notity(event Event) } type eventObserver struct { ID int Time time.Time } type eventSubject struct { Observer sync.Map } func (e *eventObserver) NotityCallback(event Event) { log.Info("输出:%s, 之后输出:%s。", event.Data, time.Since(e.Time)) } func (e *eventSubject) AddListener(observer Observer) { e.Observer.Store(observer, struct{}{}) } func (e *eventSubject) Notity(event Event) { e.Observer.Range(func(key, value interface{}) bool { if key == nil { return false } key.(Observer).NotifyCallback(event) return true }) } func Fib(n int) chan int { c := make(chan int) go func() { defer close(c) for i, j := 0, 1; i < n; i, j = i+j, i { c <- i } }() return c }