chiachan
chiachan
Published on 2020-08-09 / 649 Visits
0

Interator模式(迭代器模式)

什么是迭代器模式?

  • 将循环作用抽象化、通化后形成的模式,就叫Iterator模式。
  • 迭代器模式即一个一个遍历,意思是从含有多个元素的集合中将各个元素逐一取出。
  • 用于在数据集合中按照顺序遍历集合

示范代码(iterator.go)

package Iterator

type Iterator interface {
	Index() int
	Value() interface{}
	HasNext() bool
	Next()
}

type ArrayIterator struct {
	Iterator
	array []interface{}
	index *int
}

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

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

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

func (a *ArrayIterator) Next() {
	if a.HasNext() {
		*a.index++
	}
}

测试用例(iterator_test.go)

package Iterator

import (
	"fmt"
	"testing"
)

func TestIterator(t *testing.T) {
	arrayMembers := []interface{}{"Tom", "Mike", "Lucy", "Nick", "Piker"}
	a := 0
	iterator := &ArrayIterator{array: arrayMembers, index: &a}
	for it := iterator; iterator.HasNext(); iterator.Next() {
		index, value := it.Index(), it.Value().(string)
		if value != arrayMembers[*index] {
			fmt.Println("error...")
		}
		fmt.Println(*index, value)
	}
}