1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package main

import "fmt"

func main() {
sub := NewSubject("东北")
sub.Register(Observer{
Uid: 123,
Name: "张三",
})
sub.Register(Observer{
Uid: 124,
Name: "李四",
})

sub.NotifyAll()
}

// ObserverInterface 观察者
type ObserverInterface interface {
Notify()
}

// Observer 具体观察者
type Observer struct {
Uid int32
Name string
}

func (o Observer) Notify() {
fmt.Printf("观察者【%d】:%s \n", o.Uid, o.Name)
}

// SubjectInterface 主体,也就是观察者模式的主体
type SubjectInterface interface {
Register(o ObserverInterface)
Deregister(o ObserverInterface)
NotifyAll()
}

type Subject struct {
observerMap map[int32]Observer
name string
}

func NewSubject(name string) *Subject {
return &Subject{
name: name,
observerMap: map[int32]Observer{},
}
}

func (s *Subject) Register(o Observer) {
if _, ok := s.observerMap[o.Uid]; ok {
return
}

s.observerMap[o.Uid] = o
}

func (s *Subject) Deregister(o Observer) {
if _, ok := s.observerMap[o.Uid]; !ok {
return
}
delete(s.observerMap, o.Uid)
}

func (s *Subject) NotifyAll() {
for _, o := range s.observerMap {
o.Notify()
}
}