迭代器能在不暴露复杂数据结构内部细节的情况下遍历其中所有的元素。
package main
import "fmt"
type Iterator interface {
hasNext() bool
getNext() *User
}
type Collection interface {
createIterator() Iterator
}
type User struct {
name string
age int
}
type UserCollection struct {
users []*User
}
type UserIterator struct {
index int
users []*User
}
func (u *UserCollection) createIterator() Iterator {
return &UserIterator{
users: u.users,
}
}
func (u *UserIterator) hasNext() bool {
return u.index < len(u.users)
}
func (u *UserIterator) getNext() *User {
if u.hasNext() {
user := u.users[u.index]
u.index++
return user
}
return nil
}
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)
}
}
输出结果
User is &{name:a age:30}
User is &{name:b age:20}
参考资料
https://refactoringguru.cn/design-patterns/iterator/go/example
标签:hasNext,name,迭代,age,模式,User,type,users From: https://www.cnblogs.com/WJQ2017/p/17707289.html