设计模式:Go迭代器模式
行为型模式
1. 介绍
1.1. 定义
不需要知道集合的底层表示,顺序访问集合中的每个元素。
1.2. 角色
- 抽象迭代器(Iterator):定义遍历访问聚合的接口,通常用First()、HasNext()和Next()等。
- 具体迭代器(Concretelterator):抽象迭代器的具体实现,里面需要记录当前遍历位置。
- 抽象聚合(Aggregate):定义添加、删除、获取迭代器的抽象接口。
- 具体聚合(ConcreteAggregate):抽象聚合的具体实现。
2. 图示
3. 演示
3.1. 文件树形图
iterator
├── aggregate.go
├── concrete_aggregate.go
├── concrete_iterator.go
├── iterator.go
└── iterator_test.go
3.2. 代码
iterator.go
package iterator
type Iterator interface {
HasNext() bool
Next() int
}
concrete_iterator.go
package iterator
type ConcreteIterator struct {
list []int
offset int
}
func (c *ConcreteIterator) Next() int {
n := c.list[c.offset]
c.offset++
return n
}
func (c *ConcreteIterator) HasNext() bool {
if len(c.list) > c.offset {
return true
}
return false
}
aggregate.go
package iterator
type Aggregate interface {
Add(n int)
GetIterator() Iterator
}
concrete_aggregate.go
package iterator
type ConcreteAggregate struct {
list []int
}
func (c *ConcreteAggregate) Add(n int) {
c.list = append(c.list, n)
}
func (c *ConcreteAggregate) GetIterator() Iterator {
ci := new(ConcreteIterator)
ci.list = make([]int, len(c.list))
copy(ci.list, c.list)
return ci
}
iterator_test.go
package iterator
import (
"testing"
)
func TestConcreteAggregate_GetIterator(t *testing.T) {
ca := new(ConcreteAggregate)
ca.Add(1)
ca.Add(2)
ca.Add(3)
iterator := ca.GetIterator()
for iterator.HasNext() {
num := iterator.Next()
t.Log(num)
}
}
3.3. 测试结果
=== RUN TestConcreteAggregate_GetIterator
TestConcreteAggregate_GetIterator: iterator_test.go:15: 1
TestConcreteAggregate_GetIterator: iterator_test.go:15: 2
TestConcreteAggregate_GetIterator: iterator_test.go:15: 3
--- PASS: TestConcreteAggregate_GetIterator (0.00s)
PASS