【设计模式】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
}
相关推荐
程序员小寒6 小时前
JavaScript设计模式(九):工厂模式实现与应用
开发语言·前端·javascript·设计模式
LanceJiang7 小时前
设计模式在前端的简易实现与作用
前端·设计模式
Lyyaoo.9 小时前
【设计模式】工厂模式
java·开发语言·设计模式
楼田莉子10 小时前
设计模式:设计模式的相关概念与原则
c++·学习·设计模式
Rsun045511 天前
0设计模式使用场景
设计模式
妙蛙种子3111 天前
【Java设计模式 | 创建者模式】工厂方法模式
java·后端·设计模式·工厂方法模式
wwdoffice01101 天前
薄 膜 干 涉
设计模式
无籽西瓜a1 天前
【西瓜带你学设计模式 | 第十二期 - 装饰器模式】装饰器模式 —— 动态叠加功能实现、优缺点与适用场景
java·后端·设计模式·软件工程·装饰器模式
无籽西瓜a1 天前
【西瓜带你学设计模式 | 第十三期 - 组合模式】组合模式 —— 树形结构统一处理实现、优缺点与适用场景
java·后端·设计模式·组合模式·软件工程
Rsun045512 天前
设计模式应该怎么学
java·开发语言·设计模式