GoLang设计模式09 - 迭代器模式
迭代器模式是一种行为型模式。在这种模式中,集合结构会提供一个迭代器。通过这个迭代器可以顺序遍历集合中的每个元素而不需要暴露其具体的实现。
下面是迭代器模式的一些具体实现:
- Iterator 接口: 这个接口会定义一些基础的操作函数,如
hasNext()
或getNext()
等。通过名称就可以看出,这些方法可以帮助我们执行遍历集合、重启迭代等操作。 - Collection 接口: 这个接口代表了要被遍历的集合。在这个接口里定义了一个
createIterator
方法,该方法会返回一个Iterator
的实例。 - Concrete Iterator:
Iterator
接口的具体实现类。 - Concrete Collection:
Collection
接口的具体实现类。
在golang当前的版本(1.16或更早)中是没有泛型的,所以一些特殊情况下还是需要会用到迭代器模式。
来看下类图:
下面是示例代码:
iterator.go:
1
2
3
4
|
type iterator interface { hasNext() bool getNext() *user } |
collection.go:
1
2
3
|
type collection interface { createIterator() iterator } |
user.go:
1
2
3
4
|
type user struct { name string age int } |
userIterator.go:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
type userIterator struct { index int users []*user } func (u *userIterator) hasNext() bool { if u.index < len(u.users) { return true } return false } func (u *userIterator) getNext() *user { if u.hasNext() { user := u.users[u.index] u.index++ return user } return nil } |
userCollection.go:
1
2
3
4
5
6
7
8
9
|
type userCollection struct { users []*user } func (u *userCollection) createIterator() iterator { return &userIterator{ users: u.users, } } |
main.go:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
func main() { user1 := &user{ name: "a" , age: 30, } user2 := &user{ name: "b" , age: 20, } userCollection := &userCollection{ users: []*user{user1, user2}, } iterator := userCollection.createIterator() for iterator.hasNext() { user := iterator.getNext() fmt.Printf( "User is %+v\n" , user) } } |
输出内容:
1
2
|
User is &{name:a age:30} User is &{name:b age:20} |
代码已上传至GitHub: github / zhyea / iterator-design-pattern
END!
仅是学习笔记,难免出错,望不吝指点
转 https://www.cnblogs.com/amunote/p/15362908.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)