-
Notifications
You must be signed in to change notification settings - Fork 0
/
observer.go
72 lines (55 loc) · 1.11 KB
/
observer.go
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
package main
import (
"fmt"
"time"
)
type Event struct {
Data string
}
type Observer interface {
//更新事件
Update(*Event)
}
// 被观察的对象接口
type Subject interface {
//注册观察者
Regist(Observer)
//注销观察者
Deregist(Observer)
//通知观察者事件
Notify(*Event)
}
type ConcreteObserver struct {
Id int
}
func (co *ConcreteObserver) Update(e *Event) {
fmt.Printf("observer [%d] recieved msg: %s.\n", co.Id, e.Data)
}
type ConcreteSubject struct {
Observers map[Observer]struct{}
}
func (cs *ConcreteSubject) Regist(ob Observer) {
cs.Observers[ob] = struct{}{}
}
func (cs *ConcreteSubject) Deregist(ob Observer) {
delete(cs.Observers, ob)
}
func (cs *ConcreteSubject) Notify(e *Event) {
for ob, _ := range cs.Observers {
ob.Update(e)
}
}
func main() {
cs := &ConcreteSubject{
Observers: make(map[Observer]struct{}),
}
cobserver1 := &ConcreteObserver{1}
cobserver2 := &ConcreteObserver{2}
cs.Regist(cobserver1)
cs.Regist(cobserver2)
for i := 0; i < 5; i++ {
e := &Event{fmt.Sprintf("msg [%d]", i)}
cs.Notify(e)
time.Sleep(time.Duration(1) * time.Second)
}
}