实现迭代器模式示例,添加任务结构体、迭代器接口及具体实现,增强代码可读性
This commit is contained in:
@@ -0,0 +1,101 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
/*
|
||||
实例:
|
||||
汤宝宝有一张TODO表,记录着自己想干的事情。
|
||||
*/
|
||||
|
||||
// 任务结构体 - 迭代器元素
|
||||
type Todo struct {
|
||||
content string
|
||||
done bool
|
||||
}
|
||||
|
||||
// 迭代器接口
|
||||
type Iterator interface {
|
||||
First() *Todo
|
||||
Next() *Todo
|
||||
isDone() bool
|
||||
CurrentItem() int
|
||||
}
|
||||
|
||||
// 具体迭代器 - 汤宝宝的TODO表迭代器
|
||||
type TodoListIterator struct {
|
||||
todoList *TodoList
|
||||
current int
|
||||
}
|
||||
|
||||
func (t *TodoListIterator) First() *Todo {
|
||||
t.current = 0
|
||||
if len(t.todoList.todos) == 0 {
|
||||
return nil
|
||||
}
|
||||
return t.todoList.todos[t.current]
|
||||
}
|
||||
|
||||
func (t *TodoListIterator) Next() *Todo {
|
||||
t.current++
|
||||
if t.isDone() {
|
||||
return nil
|
||||
}
|
||||
return t.todoList.todos[t.current]
|
||||
}
|
||||
|
||||
func (t *TodoListIterator) isDone() bool {
|
||||
return t.current >= len(t.todoList.todos)
|
||||
}
|
||||
|
||||
func (t *TodoListIterator) CurrentItem() int {
|
||||
if t.isDone() {
|
||||
return len(t.todoList.todos)
|
||||
}
|
||||
return t.current + 1
|
||||
}
|
||||
|
||||
// 集合接口
|
||||
type Collection interface {
|
||||
CreateIterator() Iterator
|
||||
}
|
||||
|
||||
// 具体集合 - 汤宝宝的TODO表
|
||||
type TodoList struct {
|
||||
todos []*Todo
|
||||
}
|
||||
|
||||
func (t *TodoList) CreateIterator() Iterator {
|
||||
return &TodoListIterator{
|
||||
todoList: t,
|
||||
current: 0,
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
|
||||
fmt.Println("============= 迭代器模式 =============")
|
||||
|
||||
// 创建TODO表并添加任务
|
||||
todoList := &TodoList{
|
||||
todos: []*Todo{
|
||||
{content: "学习Go语言", done: true},
|
||||
{content: "完成设计模式作业", done: false},
|
||||
{content: "锻炼身体", done: false},
|
||||
},
|
||||
}
|
||||
|
||||
// 创建迭代器
|
||||
iterator := todoList.CreateIterator()
|
||||
|
||||
// 使用迭代器遍历TODO表
|
||||
for item := iterator.First(); !iterator.isDone(); item = iterator.Next() {
|
||||
done := "已完成"
|
||||
if !item.done {
|
||||
done = "未完成"
|
||||
}
|
||||
fmt.Println("当前第", iterator.CurrentItem(), "项任务内容:", item.content, "是否完成:", done)
|
||||
}
|
||||
|
||||
fmt.Println()
|
||||
fmt.Println("=========== 迭代器模式结束 ===========")
|
||||
}
|
||||
Reference in New Issue
Block a user