迭代器模式是一种行为设计模式, 让你能在不暴露集合底层表现形式 (列表、 栈和树等) 的情况下遍历集合中所有的元素。

使用背景

  1. 遍历集合元素:迭代器模式最典型的用途是遍历集合中的元素,如数组、列表、树等。通过提供一个迭代器,客户端可以逐个访问集合中的元素,而无需了解其内部结构。
  2. 隐藏集合的内部结构:迭代器模式可以隐藏集合的内部实现细节,使得客户端无需关心集合是如何组织和存储元素的。这样可以减少客户端与集合之间的耦合,提高系统的灵活性和可维护性。

实现代码

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
package main

import "fmt"

// Iterator 定义了迭代器接口
type Iterator interface {
HasNext() bool
Next() interface{}
}

// SliceIterator 切片迭代器
type SliceIterator struct {
slice []interface{}
index int
}

// NewSliceIterator 创建切片迭代器
func NewSliceIterator(slice []interface{}) *SliceIterator {
return &SliceIterator{slice: slice, index: 0}
}

// HasNext 判断是否有下一个元素
func (it *SliceIterator) HasNext() bool {
return it.index < len(it.slice)
}

// Next 获取下一个元素
func (it *SliceIterator) Next() interface{} {
if !it.HasNext() {
return nil
}
value := it.slice[it.index]
it.index++
return value
}

func main() {
// 创建一个切片
slice := []interface{}{"a", "b", "c", "d", "e"}

// 创建切片迭代器
iterator := NewSliceIterator(slice)

// 遍历切片并打印元素
for iterator.HasNext() {
fmt.Println(iterator.Next())
}
}


结语

迭代器模式算是比较简单的设计模式,它可以帮助我们统一遍历聚合对象中元素的方式,同时隐藏了聚合对象的内部结构,提高了代码的灵活性和可维护性。


本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。