迭代器模式是一种行为设计模式, 让你能在不暴露集合底层表现形式 (列表、 栈和树等) 的情况下遍历集合中所有的元素。
使用背景
- 遍历集合元素:迭代器模式最典型的用途是遍历集合中的元素,如数组、列表、树等。通过提供一个迭代器,客户端可以逐个访问集合中的元素,而无需了解其内部结构。
- 隐藏集合的内部结构:迭代器模式可以隐藏集合的内部实现细节,使得客户端无需关心集合是如何组织和存储元素的。这样可以减少客户端与集合之间的耦合,提高系统的灵活性和可维护性。
实现代码
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"
type Iterator interface { HasNext() bool Next() interface{} }
type SliceIterator struct { slice []interface{} index int }
func NewSliceIterator(slice []interface{}) *SliceIterator { return &SliceIterator{slice: slice, index: 0} }
func (it *SliceIterator) HasNext() bool { return it.index < len(it.slice) }
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()) } }
|
结语
迭代器模式算是比较简单的设计模式,它可以帮助我们统一遍历聚合对象中元素的方式,同时隐藏了聚合对象的内部结构,提高了代码的灵活性和可维护性。