-
Notifications
You must be signed in to change notification settings - Fork 4
/
delegate.go
68 lines (55 loc) · 1.25 KB
/
delegate.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
package ch14
import "fmt"
type DelegateSubject interface {
SetAction(action string)
GetSubjectState() string
Notify()
}
type EventHandle func()
// concrete subject
type Boss struct {
update []EventHandle
action string
}
func NewBoss() *Boss {
return &Boss{
update: make([]EventHandle, 0, 10),
}
}
func (b *Boss) SetAction(action string) {
b.action = action
}
func (b *Boss) GetSubjectState() string {
return b.action
}
func (b *Boss) AddEventHandle(handle EventHandle) {
b.update = append(b.update, handle)
}
func (b *Boss) Notify() {
for _, handle := range b.update {
handle()
}
}
// concrete observer
type DeleStockObserver struct {
name string
sub DelegateSubject
}
func NewDeleStockObserver(name string, sub DelegateSubject) *DeleStockObserver {
return &DeleStockObserver{
name: name,
sub: sub,
}
}
func (s *DeleStockObserver) CloseStockMarket() {
fmt.Printf("%s %s 关闭股票行情,继续工作!\n", s.sub.GetSubjectState(), s.name)
}
func DelegateMain() {
sub := NewBoss()
sub.SetAction("我胡汉三回来了!")
observer1 := NewDeleStockObserver("张三", sub)
observer2 := NewDeleStockObserver("李四", sub)
sub.AddEventHandle(observer1.CloseStockMarket)
sub.AddEventHandle(observer2.CloseStockMarket)
sub.Notify()
}