From 9e704d1dffc90b5023f9dc5e9eed174f77a82cde Mon Sep 17 00:00:00 2001 From: Senghoo Kim Date: Fri, 1 Apr 2016 20:13:47 +0800 Subject: [PATCH] add iterator --- 12_iterator/README.md | 5 +++ 12_iterator/iterator.go | 60 ++++++++++++++++++++++++++++++++++++ 12_iterator/iterator_test.go | 19 ++++++++++++ 3 files changed, 84 insertions(+) create mode 100644 12_iterator/README.md create mode 100644 12_iterator/iterator.go create mode 100644 12_iterator/iterator_test.go diff --git a/12_iterator/README.md b/12_iterator/README.md new file mode 100644 index 0000000..267e9e1 --- /dev/null +++ b/12_iterator/README.md @@ -0,0 +1,5 @@ +# 送代器模式 + +送代器模式用于使用相同方式送代不同类型集合或者隐藏集合类型的具体实现。 + +可以使用送代器模式使遍历同时应用送代策略,如请求新对象、过滤、处理对象等。 diff --git a/12_iterator/iterator.go b/12_iterator/iterator.go new file mode 100644 index 0000000..593d918 --- /dev/null +++ b/12_iterator/iterator.go @@ -0,0 +1,60 @@ +package iterator + +import "fmt" + +type Aggregate interface { + Iterator() Iterator +} + +type Iterator interface { + First() + IsDone() bool + Next() interface{} +} + +type Numbers struct { + start, end int +} + +func NewNumbers(start, end int) *Numbers { + return &Numbers{ + start: start, + end: end, + } +} + +func (n *Numbers) Iterator() Iterator { + return &NumbersIterator{ + numbers: n, + next: n.start, + } +} + +type NumbersIterator struct { + numbers *Numbers + next int +} + +func (i *NumbersIterator) First() { + i.next = i.numbers.start +} + +func (i *NumbersIterator) IsDone() bool { + return i.next > i.numbers.end +} + +func (i *NumbersIterator) Next() interface{} { + if !i.IsDone() { + next := i.next + i.next++ + return next + } + return nil +} + +func IteratorPrint(i Iterator) { + for i.First(); !i.IsDone(); { + c := i.Next() + fmt.Printf("%#v\n", c) + } +} diff --git a/12_iterator/iterator_test.go b/12_iterator/iterator_test.go new file mode 100644 index 0000000..a508289 --- /dev/null +++ b/12_iterator/iterator_test.go @@ -0,0 +1,19 @@ +package iterator + +func ExampleIterator() { + var aggregate Aggregate + aggregate = NewNumbers(1, 10) + + IteratorPrint(aggregate.Iterator()) + // Output: + // 1 + // 2 + // 3 + // 4 + // 5 + // 6 + // 7 + // 8 + // 9 + // 10 +}