概念
迭代器模式(IteratorPattern):提供一种方法顺序访问一个聚集对象中各个元素,而又不暴露该对象的内部表示。
需求
利用迭代器模式实现售票员售票
UML图
代码
抽象聚集类
type Aggregate interface {
CreateIterator() Iterator
}
抽象迭代器类
type Iterator interface {
First() interface{}
Next() interface{}
IsDone() bool
CurrentItem() interface{}
}
具体聚集类
type ConcreteAggregate struct {
Items []interface{}
}
func (c *ConcreteAggregate) CreateIterator() Iterator {
return &ConcreteIterator{Aggregate: *c}
}
具体迭代器类
type ConcreteIterator struct {
Aggregate ConcreteAggregate
current int64
}
func (c *ConcreteIterator) First() interface{} {
return c.Aggregate.Items[0]
}
func (c *ConcreteIterator) Next() interface{} {
var ret interface{}
c.current++
if c.current < int64(len(c.Aggregate.Items)) {
ret = c.Aggregate.Items[c.current]
}
return ret
}
func (c *ConcreteIterator) IsDone() bool {
return c.current < int64(len(c.Aggregate.Items))
}
func (c *ConcreteIterator) CurrentItem() interface{} {
return c.Aggregate.Items[c.current]
}
测试
//迭代器模式
a := iteratorPattern.ConcreteAggregate{}
a.Items = append(a.Items, "大鸟")
a.Items = append(a.Items, "小菜")
a.Items = append(a.Items, "行李")
a.Items = append(a.Items, "老外")
a.Items = append(a.Items, "公交内部员工")
a.Items = append(a.Items, "小偷")
i := iteratorPattern.ConcreteIterator{Aggregate: a}
for i.IsDone() {
fmt.Printf("%v 请买车票", i.CurrentItem())
fmt.Println()
i.Next()
}