1
0
Fork 0
design-patterns/go/iterator/main.go

102 lines
1.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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("=========== 迭代器模式结束 ===========")
}