-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfacade.go
82 lines (70 loc) · 1.47 KB
/
facade.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
75
76
77
78
79
80
81
82
package facade
// 【外观模式】
import "fmt"
// 统一接口
type List interface {
Add(idx int, e interface{}) bool
AddLast(e interface{}) bool
Remove(idx int) (interface{}, bool)
RemoveLast() (interface{}, bool)
Get(idx int) (interface{}, bool)
}
type ArrayList struct {
ele []interface{}
size int
}
func NewArrayList(capacity int) *ArrayList {
if capacity < 16 {
capacity = 16
}
return &ArrayList{
ele: make([]interface{}, 0, capacity),
size: 0,
}
}
func ArrayListOf(ele ...interface{}) *ArrayList {
return &ArrayList{
ele: ele,
size: len(ele),
}
}
func (a *ArrayList) Add(idx int, e interface{}) bool {
if idx > a.size {
return false
}
a.ele = append(a.ele, nil)
copy(a.ele[idx+1:], a.ele[idx:]) // 后移一位, 把idx位置空出来
a.ele[idx] = e
a.size++
return true
}
func (a *ArrayList) AddLast(e interface{}) bool {
a.ele = append(a.ele, e)
a.size++
return true
}
func (a *ArrayList) Remove(idx int) (interface{}, bool) {
if idx >= a.size {
return nil, false
}
e := a.ele[idx]
a.ele = append(a.ele[:idx], a.ele[idx+1:]...) // 跳过idx元素
a.size--
return e, true
}
func (a *ArrayList) RemoveLast() (interface{}, bool) {
e := a.ele[a.size-1]
a.ele = append(a.ele[:a.size-1])
a.size--
return e, true
}
func (a *ArrayList) Get(idx int) (interface{}, bool) {
if idx >= a.size {
return nil, false
}
e := a.ele[idx]
return e, true
}
func (a *ArrayList) String() string {
return fmt.Sprintf("size=%v, %v", a.size, a.ele)
}