将观察者注册到事件的回调函数,如不需要则从回调中移除
package main
// 注册回调接口的思路类似
// 将观察者注册到事件的回调函数,如不需要则从回调中移除
import (
"log"
"sync"
"time"
)
type Event struct {
Data int
}
type Observer interface {
NotifyCallback(event Event)
}
func NewObserver(id int) Observer {
return &eventObserver{Id: id, Time: time.Now()}
}
type eventObserver struct {
Id int
Time time.Time
}
func (e *eventObserver) NotifyCallback(event Event) {
log.Printf("Observer %d Received: %d after %v\n", e.Id, event.Data, time.Since(e.Time))
}
type Subject interface {
AddListener(observer Observer)
RemoveListener(observer Observer)
Notify(event Event)
}
func NewSubject() Subject {
return &eventSubject{
Observers: sync.Map{},
}
}
type eventSubject struct {
Observers sync.Map
}
func (e *eventSubject) AddListener(observer Observer) {
e.Observers.Store(observer, struct{}{})
}
func (e *eventSubject) RemoveListener(observer Observer) {
e.Observers.Delete(observer)
}
func (e *eventSubject) Notify(event Event) {
e.Observers.Range(
func(key, value interface{}) bool {
if key == nil {
return false
}
key.(Observer).NotifyCallback(event)
return true
},
)
}
func main() {
ob1 := NewObserver(1)
ob2 := NewObserver(2)
subject := NewSubject()
subject.AddListener(ob1) // 注册观察者1
subject.AddListener(ob2) // 注册观察者2
subject.Notify(Event{Data: 100})
subject.RemoveListener(ob2) // 移除观察者2
subject.Notify(Event{Data: 900})
}
发表回复