文章目录
- [十七、iterator 迭代器模式](#十七、iterator 迭代器模式)
-
- [17.1 user_slice](#17.1 user_slice)
-
- [17.1.1 collection_test.go](#17.1.1 collection_test.go)
- [17.1.2 collection.go](#17.1.2 collection.go)
- [17.1.3 iterator.go](#17.1.3 iterator.go)
- [17.1.4 user.go](#17.1.4 user.go)
十七、iterator 迭代器模式
https://refactoringguru.cn/design-patterns/iterator
为了集合数据的安全性, 或方便迭代, 可以用迭代器接口. 屏蔽复杂的内部逻辑, 外部只能使用迭代器遍历
17.1 user_slice
bash
├── collection.go
├── collection_test.go
├── iterator.go
├── readme.md
└── user.go
17.1.1 collection_test.go
go
package _71user_slice
import (
"fmt"
"testing"
)
/*
=== RUN TestCollection
1 Tom
2 Jack
--- PASS: TestCollection (0.00s)
PASS
*/
func TestCollection(t *testing.T) {
c := UserCollection{users: []*User{&User{"1", "Tom"}, {"2", "Jack"}}}
iter := c.createIterator()
for iter.hasNext() {
v := iter.getNext()
fmt.Println(v.ID, v.Name)
}
}
17.1.2 collection.go
go
package _71user_slice
type Collection interface {
createIterator() Iterator
}
type UserCollection struct {
users []*User
}
func (uc *UserCollection) createIterator() Iterator {
return &userIterator{
users: uc.users,
}
}
17.1.3 iterator.go
go
package _71user_slice
type Iterator interface {
hasNext() bool
getNext() *User
}
type userIterator struct {
index int
users []*User
}
func (ui *userIterator) hasNext() bool {
return ui.index < len(ui.users)
}
func (ui *userIterator) getNext() *User {
if ui.hasNext() {
v := ui.users[ui.index]
ui.index++
return v
}
return nil
}
17.1.4 user.go
go
package _71user_slice
type User struct {
ID string
Name string
}