设计模式——迭代器模式

2020-10-30  本文已影响0人  DevilRoshan

什么是迭代器模式?

提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。

实现

// 抽象迭代器
type Iterator interface {
    Index() int
    Value() interface{}
    HasNext() bool
    Next()
}

// 具体容器
type ArrayIterator struct {
    array []interface{}
    index *int
}

func NewArrayIterator() *ArrayIterator {
    return &ArrayIterator{}
}

func (this *ArrayIterator) Index() *int {
    return this.index
}

func (this *ArrayIterator) Value() interface{} {
    return this.array[*this.index]
}

func (this *ArrayIterator) HasNext() bool {
    return *this.index+1 <= len(this.array)
}

func (this *ArrayIterator) Next() {
    if this.HasNext() {
        *this.index++
    }
}
func TestArrayIterator(t *testing.T) {
    array := []interface{}{1, 3, 4, 6, 7, 5, 2}
    a := 0
    iterator := ArrayIterator{index:&a, array:array}
    for iter := iterator; iter.HasNext() ;iter.Next()  {
        index, value := iter.Index(), iter.Value().(int)
        for value != array[*index] {
            fmt.Println("error")
        }
        fmt.Println(*index, value)
    }
}
// === RUN   TestArrayIterator
// 0 1
// 1 3
// 2 4
// 3 6
// 4 7
// 5 5
// 6 2
// --- PASS: TestArrayIterator (0.00s)
// PASS

优点

缺点

使用场景

上一篇 下一篇

猜你喜欢

热点阅读