【设计模式】17、iterator 迭代器模式

文章目录

  • [十七、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
}
相关推荐
GodKeyNet1 小时前
设计模式-模板模式
设计模式·模板模式
缘来是庄5 小时前
设计模式之建造者模式
java·设计模式·建造者模式
铛铛啦啦啦7 小时前
“对象创建”模式之原型模式
设计模式·原型模式
牛奶咖啡138 小时前
学习设计模式《十六》——策略模式
学习·设计模式·策略模式·认识策略模式·策略模式的优缺点·何时选用策略模式·策略模式的使用示例
OpenC++9 小时前
【C++】观察者模式
c++·观察者模式·设计模式
一块plus10 小时前
2025 年值得一玩的最佳 Web3 游戏
算法·设计模式·程序员
缘来是庄11 小时前
设计模式之代理模式
java·设计模式·代理模式
勤奋的知更鸟12 小时前
Java 编程之策略模式详解
java·设计模式·策略模式
暮乘白帝过重山12 小时前
设计模式篇:灵活多变的策略模式
设计模式·策略模式
GodKeyNet12 小时前
设计模式-策略模式
设计模式·策略模式