-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobserver_test.go
60 lines (47 loc) · 869 Bytes
/
observer_test.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
package observer
import (
"fmt"
"testing"
)
// 观察者模式
// 观察者
type IObserver interface {
Update(msg string)
}
type ISubject interface {
Register(obs ISubject)
Remove(obs ISubject)
Notify(msg string)
}
type Subject struct {
obss []IObserver
}
func (s *Subject) Register(obs IObserver) {
s.obss = append(s.obss, obs)
}
func (s *Subject) Remove(obs IObserver) {
for i, ob := range s.obss {
if ob == obs {
s.obss = append(s.obss[:i], s.obss[i+1:]...)
}
}
}
func (s *Subject) Notify(msg string) {
for _, o := range s.obss {
o.Update(msg)
}
}
type Obs1 struct{}
func (o Obs1) Update(msg string) {
fmt.Printf("obs1: %s", msg)
}
type Obs2 struct{}
func (o Obs2) Update(msg string) {
fmt.Printf("obs2: %s", msg)
}
func TestObs(t *testing.T) {
sub := &Subject{}
sub.Register(&Obs1{})
sub.Register(&Obs2{})
sub.Notify("hi")
}