创建文件Observer.go
package observer type Observer interface { Update(subject *Subject) }
创建文件Reader.go
package observer import "fmt" // 读取类 type Reader struct { Name string } func NewReader(name string) *Reader { return &Reader{Name: name} } func (r *Reader) Update(s *Subject) { fmt.Printf("%s 收到 %s\n", r.Name, s.context) }
创建文件Subject.go
package observer type Subject struct { obs []Observer //群聊 context string // 更新群聊信息 } func NewSubject() *Subject { return &Subject{obs: make([]Observer, 0)} } func (s *Subject) Attch(o Observer) { s.obs = append(s.obs, o) // 加入群聊 } func (s *Subject) notify() { for _, o := range s.obs { // 每个人都发一次 o.Update(s) // 更新通知 } } func (s *Subject) UpdateContext(context string) { s.context = context s.notify() // 更新之后通知 }
main.go
package main import "test/design/observer" func main() { subject := observer.NewSubject() r1 := observer.NewReader("Jackey1") r2 := observer.NewReader("Jackey2") r3 := observer.NewReader("Jackey3") subject.Attch(r1) subject.Attch(r2) subject.Attch(r3) subject.UpdateContext("hello") r4 := observer.NewReader("Jackey4") subject.Attch(r4) subject.UpdateContext("你好") }