-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiterator.go
83 lines (68 loc) · 1.33 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package iterator
// Aggregate 集合
type Aggregate interface {
Iterator() Iterator
}
// Iterator 迭代器
type Iterator interface {
HasNext() bool
Next() interface{}
}
type Book struct {
name string
}
func NewBook(name string) *Book {
return &Book{
name: name,
}
}
func (b *Book) GetName() string {
return b.name
}
// BookShelf 具体集合(concrete aggregate)
type BookShelf struct {
books []*Book
last int
}
func NewBookShelf(maxSize int) *BookShelf {
return &BookShelf{
books: make([]*Book, 0, maxSize),
last: 0,
}
}
func (b *BookShelf) GetBookAt(index int) *Book {
return b.books[index]
}
func (b *BookShelf) AppendBook(book *Book) {
b.books = append(b.books, book)
b.last++
}
func (b *BookShelf) GetLength() int {
return b.last
}
func (b *BookShelf) Iterator() Iterator {
return NewBookShelfIterator(b)
}
// BookShelfIterator 具体迭代器(concrete iterator)
type BookShelfIterator struct {
bookShelf *BookShelf
index int
}
func NewBookShelfIterator(bookShelf *BookShelf) *BookShelfIterator {
return &BookShelfIterator{
bookShelf: bookShelf,
index: 0,
}
}
func (b *BookShelfIterator) HasNext() bool {
if b.index < b.bookShelf.GetLength() {
return true
} else {
return false
}
}
func (b *BookShelfIterator) Next() interface{} {
book := b.bookShelf.GetBookAt(b.index)
b.index++
return book
}