【设计模式】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
}
相关推荐
on the way 1236 小时前
结构性设计模式之Flyweight(享元)
java·设计模式·享元模式
暴躁哥10 小时前
深入理解设计模式之访问者模式
设计模式·访问者模式
佩奇的技术笔记10 小时前
从Java的JDK源码中学设计模式之装饰器模式
java·设计模式·装饰器模式
on the way 12310 小时前
结构型设计模式之Proxy(代理)
设计模式·代理模式
YGGP13 小时前
【结构型模式】装饰器模式
设计模式
将编程培养成爱好16 小时前
《复制粘贴的奇迹:小明的原型工厂》
c++·设计模式·原型模式
liang_jy16 小时前
设计模式中的几大原则
设计模式·面试
huangyujun992012318 小时前
设计模式杂谈-模板设计模式
java·设计模式
magic 24519 小时前
Java设计模式:责任链模式
java·设计模式·责任链模式
YGGP1 天前
【结构型模式】代理模式
设计模式