4

设计模式--迭代器(Iterator)模式

 2 years ago
source link: https://segmentfault.com/a/1190000040406672
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

  • 迭代抽象:访问一个聚合对象的内部而无需暴露它的内部表示
  • 迭代多态:为遍历不同的集合结构提供一个统一的接口,从而支持同样的算法在不同的集合结构上进行操作
  • 迭代器的健壮性考虑:遍历的同时更改迭代器所在的集合结构,会导致问题

Go语言代码实现

iterator.go

package Iterator

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

type ArrayIterator struct {
   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 TestArrayIterator(t *testing.T) {
   array := []interface{}{1,3,9,2,8,7}
   a := 0
   iterator := ArrayIterator{array: array, index: &a}
   for it := iterator; iterator.HasNext(); iterator.Next(){
      index, value := it.Index(), it.Value().(int)
      for value != array[*index]{
         fmt.Println("error")
      }
      fmt.Println(*index, value)
   }
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK