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

server/2024/9/24 13:22:21/

文章目录

  • 十七、iterator 迭代器模式
    • 17.1 user_slice
      • 17.1.1 collection_test.go
      • 17.1.2 collection.go
      • 17.1.3 iterator.go
      • 17.1.4 user.go
    • 17.2 book_shelf
      • 17.2.1 book_shelf_test.go
      • 17.2.2 book_shelf.go
      • 17.2.3 iterator.go
      • 17.2.4 book.go

十七、iterator 迭代器模式

https://refactoringguru.cn/design-patterns/iterator

为了集合数据的安全性, 或方便迭代, 可以用迭代器接口. 屏蔽复杂的内部逻辑, 外部只能使用迭代器遍历

源码路径:godp/17iterator at master · datager/godp · GitHub

17.1 user_slice

├── collection.go
├── collection_test.go
├── iterator.go
├── readme.md
└── user.go

17.1.1 collection_test.go

package _71user_sliceimport ("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

package _71user_slicetype Collection interface {createIterator() Iterator
}type UserCollection struct {users []*User
}func (uc *UserCollection) createIterator() Iterator {return &userIterator{users: uc.users,}
}

17.1.3 iterator.go

package _71user_slicetype Iterator interface {hasNext() boolgetNext() *User
}type userIterator struct {index intusers []*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

package _71user_slicetype User struct {ID   stringName string
}

17.2 book_shelf

图解设计模式 1.7 练习题

iterator 模式, 可以抽象出 迭代的操作, 无论内部数据结构是数组, 或链表, 或树, 都可以. 外部都可以用同样的接口访问.

本例, 分别用 数组, 和链表实现

├── book.go
├── book_shelf.go
├── book_shelf_test.go
├── iterator.go
└── readmd.md

17.2.1 book_shelf_test.go

package _72bookshelfimport ("github.com/stretchr/testify/require""testing"
)/*
=== RUN   TestBookShelfbook_shelf_test.go:21: 算子开发book_shelf_test.go:21: 编译器book_shelf_test.go:21: 算子开发book_shelf_test.go:21: 编译器--- PASS: TestBookShelf (0.00s)
PASS
*/
func TestBookShelf(t *testing.T) {bookShelves := []bookShelf{NewBookShelfBySlice(), NewBookShelfByList()}for _, bs := range bookShelves {bookNames := []string{"算子开发", "编译器"} // 测试数据for _, name := range bookNames {bs.addBook(NewBook(name))}it := bs.iterator()idx := 0for it.hasNext() {b := it.next()require.EqualValues(t, bookNames[idx], b.getName())t.Log(b.getName())idx++}}
}

17.2.2 book_shelf.go

package _72bookshelfimport "container/list"// 书架接口
type bookShelf interface {// 创建迭代器iterator() iterator// 辅助业务:addBook(book)
}// 书架: 数组实现
type bookShelfBySlice struct {books []book
}func NewBookShelfBySlice() bookShelf {return &bookShelfBySlice{make([]book, 0)}
}func (bs *bookShelfBySlice) iterator() iterator {return NewBookShelfBySliceIterator(bs)
}func (bs *bookShelfBySlice) addBook(b book) {bs.books = append(bs.books, b)
}// 书架: 链表实现
type bookShelfByList struct {bookList *list.List
}func NewBookShelfByList() bookShelf {return &bookShelfByList{bookList: list.New(),}
}func (bs *bookShelfByList) iterator() iterator {return NewBookShelfByListIterator(bs)
}func (bs *bookShelfByList) addBook(b book) {bs.bookList.PushBack(b)
}

17.2.3 iterator.go

package _72bookshelfimport "container/list"// 迭代器接口
type iterator interface {hasNext() boolnext() book
}// -------
// 书架迭代器: 基于数组的书架
type bookShelfBySliceIterator struct {index     int               // 迭代器下标bookShelf *bookShelfBySlice // 被迭代的对象
}func (bsi *bookShelfBySliceIterator) hasNext() bool {return bsi.index < len(bsi.bookShelf.books)
}func (bsi *bookShelfBySliceIterator) next() book {v := bsi.bookShelf.books[bsi.index]bsi.index++return v
}func NewBookShelfBySliceIterator(bs *bookShelfBySlice) iterator {return &bookShelfBySliceIterator{bookShelf: bs, index: 0}
}// -------
// 书架迭代器: 基于链表的书架
type bookShelfByListIterator struct {curBook   *list.Element    // 迭代器下标bookShelf *bookShelfByList // 被迭代的对象
}func (bsl *bookShelfByListIterator) hasNext() bool {return bsl.curBook != nil
}func (bsl *bookShelfByListIterator) next() book {v := bsl.curBookbsl.curBook = bsl.curBook.Next()return v.Value.(book)
}func NewBookShelfByListIterator(bs *bookShelfByList) iterator {return &bookShelfByListIterator{bookShelf: bs, curBook: bs.bookList.Front()}
}

17.2.4 book.go

package _72bookshelfimport ("math/rand""time"
)type book interface {getName() string
}type bookImpl struct {id   intname string
}func (b *bookImpl) getName() string {return b.name
}func NewBook(name string) book {rand.NewSource(time.Now().UnixMilli())return &bookImpl{id:   rand.Int(),name: name,}
}

http://www.ppmy.cn/server/36811.html

相关文章

C语言双向链表

前面我们已经学完了单链表的知识点&#xff08;如果还没有看过的主页有哦~&#xff09;&#xff0c;这篇博客我们就来探讨探讨单链表的孪生弟弟——双向链表。 目录 1.链表的分类 2.双向链表的结构 3.双向链表的实现 3.1 List.h 3.2 List.c 4.书写要点总结说明 4.1为什…

XSS攻击分析---(原理、危害、防御、应急响应)

1、攻击原理 造成XSS漏洞的原因就是&#xff0c;对攻击者的输入没有经过严格的控制&#xff0c;使得攻击者通过巧妙的方法注入恶意指令代码到网页&#xff0c;进行加载并执行。这些恶意网页程序通常是JavaScript&#xff0c;但实际上也可以包括Java&#xff0c; VBScript&…

数据可视化准备:动态识别echarts的横纵坐标数据字段

前言 继上一篇文章 自动选择图表类型&#xff1a;基于数据特征智能决策 分析了如何根据sql和数据结果判断应该自动使用哪种图表类型&#xff0c;本文继续将图表的x轴和y轴横纵坐标识别出来&#xff0c;基本一个二维数据类普通图表就可以直接输出为echarts参数了。 在数据可视…

Android 桌面小组件 AppWidgetProvider

Android 桌面小组件 AppWidgetProvider 简介 小组件就是可以添加到手机桌面的窗口。点击窗口可以进入应用或者进入应用的某一个页面。 widget 组件 如需创建 widget&#xff0c;您需要以下基本组件&#xff1a; AppWidgetProviderInfo 对象 描述 widget 的元数据&#xff0…

解决连接不上VPN问题

解决连接不上VPN问题 错误描述&#xff1a;错误描述&#xff1a; 错误描述&#xff1a; 无法建立计算机与VPN服务器之间的网络连接&#xff0c;因为远程服务器未响应。这可能是因为未将计算机与远程服务器之间的某种网络设备&#xff08;如防火墙、NAT、路由器等&#xff09;配…

node.js中的断言

assert.ok(value, [message])&#xff1a;如果value不为真&#xff0c;则抛出一个AssertionError&#xff0c;可选地包含message。 const assert require(assert); assert.ok(true); // 没有错误 assert.ok(false, 这里应该是true); // 抛出 AssertionError: 这里应该是tru…

远程桌面连接不上,远程桌面连接不上的专业解决策略

在信息技术领域&#xff0c;远程桌面连接是一种非常重要的工具&#xff0c;它允许用户从任何地点、任何时间访问和操作远程计算机。然而&#xff0c;当远程桌面连接出现问题时&#xff0c;可能会严重影响工作效率。以下是一些可能导致远程桌面连接不上的原因以及相应的解决方案…

通过颜色学习css

文章目录 1.生成html2.添加css链接3.将h1标签text-align元素4.添加div标签4.1、为类marker添加元素4.2、添加两个新的div标签4.3、修改div标签的类型并修改css元素4.4、为类container添加元素4.5、以数字形式添加颜色4.5、container添加padding属性4.6、组合css中的颜色属性4.7…