【设计模式】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
}
相关推荐
七月丶1 天前
别再手动凑 PR 了:这个 AI Skill 会按仓库习惯自动建分支、拆提交、提 PR
人工智能·设计模式·程序员
刀法如飞1 天前
从程序员到架构师:6大编程范式全解析与实践对比
设计模式·系统架构·编程范式
九狼1 天前
Flutter + Riverpod +MVI 架构下的现代状态管理
设计模式
静水流深_沧海一粟2 天前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder2 天前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
阿星AI工作室2 天前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
_哆啦A梦3 天前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding
阿闽ooo6 天前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式
小米4966 天前
js设计模式 --- 工厂模式
设计模式