迭代器模式
被迭代对象接口
package iterator
type Aggregate interface {
createIterator() Iterator
}
具体被迭代的对象
package iterator
type array []int
func NewArray(args ...int) array {
var arr array
for _, v := range args {
arr = append(arr, v)
}
return arr
}
func (a array) createIterator() Iterator {
return &SliceIterator{
object: NewArray(a...),
index: 0,
}
}
迭代器接口
package iterator
type Iterator interface {
hasNext() bool
getNext() int
}
迭代器实现
package iterator
type SliceIterator struct {
object array
index int
}
func (s *SliceIterator) getNext() int {
res := s.object[s.index]
s.index++
return res
}
func (s *SliceIterator) hasNext() bool {
if s.index < len(s.object) {
return true
}
return false
}
测试文件
package iterator
func TestIterator(t *testing.T) {
iter := NewArray(4, 2, 3, 8).createIterator()
for iter.hasNext() {
fmt.Printf("%v\n", iter.getNext())
}
}
标签:index,return,迭代,iterator,int,模式,array
From: https://www.cnblogs.com/mathsmouse/p/16981798.html