1、介绍
提供一种方法顺序访问一个聚合对象中的各个元素,而又不需要暴露该对象的内部表示。
迭代器模式的结构
2、示例
示例代码:
package main
import (
"fmt"
)
//迭代器接口
type Iterator interface {
First()
IsDone() bool
Next() interface{}
}
//迭代的数据集
type Aggregate interface {
Iterator() Iterator
}
type Numbers struct {
start, end int
}
//实现迭代器接口对应的功能
type NumbersIterator struct {
numbers *Numbers
next int
}
func (i *NumbersIterator) First() {
i.next = i.numbers.start
}
func (i *NumbersIterator) IsDone() bool {
return i.next > i.numbers.end
}
func (i *NumbersIterator) Next() interface{} {
if !i.IsDone() {
next := i.next
i.next++
return next
}
return nil
}
func (n *Numbers) Iterator() Iterator {
return &NumbersIterator{
numbers: n,
next: n.start,
}
}
func NewNumbers(start,end int)*Numbers {
return &Numbers{
start: start,
end: end,
}
}
func IteratorPrint(i Iterator) {
for i.First();!i.IsDone();{
c:=i.Next()
fmt.Printf("%v\n",c)
}
}
func main() {
//var aggregate Aggregate
//aggregate=NewNumbers(1,10)
//IteratorPrint(aggregate.Iterator())
//等价于:
numbers := NewNumbers(1, 10)
IteratorPrint(numbers.Iterator())
}
UML图: