迭代器模式(Iterator Pattern)是一种行为设计模式,它提供了一种方法顺序访问聚合对象中的各个元素,而无需暴露其内部表示。通过将遍历逻辑封装在迭代器中,客户端可以以统一的方式访问不同类型的集合。
隐藏复杂性:将集合的内部结构与遍历逻辑分离,避免直接操作集合。
提高复用性:不同的集合可以通过相同的迭代器接口进行遍历。
支持多种遍历方式:可以通过实现不同的迭代器来支持多种遍历方式(如正向、反向等)。
需要对一个聚合对象进行多种方式的遍历时。
需要为遍历过程增加新的功能时(如过滤、条件判断等)。
需要隐藏集合的内部结构时。
以下是一个简单的例子,展示如何使用迭代器模式遍历一个整数集合:
package main
import "fmt"
// Aggregate 聚合接口
type Aggregate interface {
CreateIterator() Iterator
}
// Iterator 迭代器接口
type Iterator interface {
HasNext() bool
Next() int
}
// ConcreteAggregate 具体聚合类
type ConcreteAggregate struct {
items []int
}
func (ca *ConcreteAggregate) CreateIterator() Iterator {
return &ConcreteIterator{aggregate: ca, index: 0}
}
// ConcreteIterator 具体迭代器类
type ConcreteIterator struct {
aggregate *ConcreteAggregate
index int
}
func (ci *ConcreteIterator) HasNext() bool {
return ci.index < len(ci.aggregate.items)
}
func (ci *ConcreteIterator) Next() int {
if ci.HasNext() {
item := ci.aggregate.items[ci.index]
ci.index++
return item
}
panic("No more elements")
}
func main() {
// 创建一个聚合对象
aggregate := &ConcreteAggregate{items: []int{1, 2, 3, 4, 5}}
// 获取迭代器
iterator := aggregate.CreateIterator()
// 遍历集合
for iterator.HasNext() {
fmt.Println(iterator.Next())
}
}