forked from qq570850096/awesome-golang-DesignPattern
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIterator.go
64 lines (51 loc) · 1 KB
/
Iterator.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
package BehavioralType
// 抽象迭代器
type Iterator interface {
Next() interface{}
HasNext() bool
}
// 具体迭代器
type ConcreteIterator struct {
index int
size int
con Aggregate
}
func (c *ConcreteIterator) Next() interface{} {
if c.HasNext() {
res := c.con.GetElement(c.index)
c.index++
return res
}
return nil
}
func (c *ConcreteIterator) HasNext() bool {
return c.index < c.size
}
// 抽象聚集
type Aggregate interface {
Add(obj interface{})
CreateIterator() Iterator
GetElement(index int) interface{}
Size() int
}
// 具体聚集
type ConcreteAggregate struct {
//私有存储容器
docker []interface{}
}
func (c *ConcreteAggregate) Add(obj interface{}) {
c.docker = append(c.docker,obj)
}
func (c *ConcreteAggregate) CreateIterator() Iterator {
return &ConcreteIterator{
index: 0,
size: c.Size(),
con: c,
}
}
func (c *ConcreteAggregate) GetElement(index int) interface{} {
return c.docker[index]
}
func (c *ConcreteAggregate) Size() int {
return len(c.docker)
}