《大话设计模式-Golang》迭代器模式

文章介绍了如何使用迭代器模式在Go语言中实现售票员售票的过程。通过定义抽象聚集类和抽象迭代器类,以及具体实现的聚集类和迭代器类,实现了对售票对象的有序访问,而无需暴露其内部结构。在测试部分,创建了一个具体的聚集对象,添加了多个购票者,然后通过迭代器进行售票操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

概念

迭代器模式(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()
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值