-
Notifications
You must be signed in to change notification settings - Fork 52
/
chain.go
74 lines (63 loc) · 1.03 KB
/
chain.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
72
73
74
package chain
type Chain struct {
head *node
tail *node
}
type node struct {
prev *node
next *node
fn func()
}
func NewChain() *Chain {
return &Chain{}
}
// AddToHead 添加头部
func (c *Chain) AddToHead(fn func()) {
if c.head == nil {
c.head = &node{fn: fn}
c.tail = c.head
} else {
head := &node{fn: fn, next: c.head}
c.head.prev = head
c.head = head
}
}
// AddToTail 添加到尾部
func (c *Chain) AddToTail(fn func()) {
if c.tail == nil {
c.tail = &node{fn: fn}
c.head = c.tail
} else {
tail := &node{fn: fn, prev: c.tail}
c.tail.next = tail
c.tail = tail
}
}
// FireHead 从头部开始执行
func (c *Chain) FireHead() {
head := c.head
for head != nil {
if head.fn != nil {
head.fn()
}
next := head.next
head.next = nil
head = next
}
c.head = nil
c.tail = nil
}
// FireTail 从尾部开始执行
func (c *Chain) FireTail() {
tail := c.tail
for tail != nil {
if tail.fn != nil {
tail.fn()
}
prev := tail.prev
tail.prev = nil
tail = prev
}
c.head = nil
c.tail = nil
}