From 64daf5eb8b3add34ae779e8e36e133f4b5034516 Mon Sep 17 00:00:00 2001 From: Edward Date: Mon, 4 May 2020 11:24:28 +0800 Subject: [PATCH] update iterator pattern --- behavior/04_iterator/iterator.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/behavior/04_iterator/iterator.go b/behavior/04_iterator/iterator.go index 7552e2e..e4d41f0 100644 --- a/behavior/04_iterator/iterator.go +++ b/behavior/04_iterator/iterator.go @@ -26,14 +26,15 @@ type ScenicArea struct { //PotsIterator 该对象的目的就是为了隐藏景区本身 //PotsIterator 实现为一个游标迭代器 type PotsIterator struct { - cursor int - potsSlice []IPot + cursor, count int + potsSlice []IPot } //Iterator 返回一个接待 func (s *ScenicArea) Iterator() Iterator { return &PotsIterator{ cursor: 0, + count: s.count, potsSlice: s.pots, } } @@ -63,16 +64,15 @@ func (s *PotsIterator) FirstPot() IPot { //IsLastPot 判断游标的位置 func (s *PotsIterator) IsLastPot() bool { - return s.cursor == -1 + return s.cursor == s.count } //Next 去路线上的下一个景点 func (s *PotsIterator) Next() IPot { - if s.cursor+1 == len(s.potsSlice) { - s.cursor = -1 //设置到最后 + s.cursor++ + if s.IsLastPot() { return nil } - s.cursor++ return s.potsSlice[s.cursor] }