1
0
Fork 0

实现迭代器模式示例,添加任务结构体、迭代器接口及具体实现,增强代码可读性

This commit is contained in:
IvisTang 2026-01-06 02:03:46 +08:00
parent cc215c9d70
commit f579b1a5cc
3 changed files with 298 additions and 0 deletions

101
go/iterator/main.go Normal file
View File

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

105
python/iterator/main.py Normal file
View File

@ -0,0 +1,105 @@
"""
实例
汤宝宝有一张TODO表记录着自己想干的事情
"""
from abc import ABC, abstractmethod
# 任务结构体 - 迭代器元素
class Todo:
content: str
done: bool
def __init__(self, content: str, done: bool = False):
self.content = content
self.done = done
# 集合接口
class Collection(ABC):
@abstractmethod
def CreateIterator(self) -> "Iterator":
pass
# 具体集合 - 汤宝宝的TODO表
class TodoList(Collection):
todos: list[Todo]
def __init__(self, todos: list[Todo]):
self.todos = todos
def CreateIterator(self) -> "Iterator":
return TodoListIterator(self)
# 迭代器接口
class Iterator(ABC):
@abstractmethod
def First(self) -> Todo:
pass
@abstractmethod
def Next(self) -> Todo | None:
pass
@abstractmethod
def isDone(self) -> bool:
pass
@abstractmethod
def CurrentItem(self) -> int:
pass
# 具体迭代器 - 汤宝宝的TODO表迭代器
class TodoListIterator(Iterator):
def __init__(self, todo_list: "TodoList"):
self._todo_list = todo_list
self._current = 0
def First(self) -> Todo:
self._current = 0
return self._todo_list.todos[self._current]
def Next(self) -> Todo | None:
self._current += 1
if not self.isDone():
return self._todo_list.todos[self._current]
return None
def isDone(self) -> bool:
return self._current >= len(self._todo_list.todos)
def CurrentItem(self) -> int:
if self.isDone():
return len(self._todo_list.todos)
return self._current + 1
if __name__ == "__main__":
print("============= 迭代器模式 =============")
# 创建TODO表并添加任务
todo_list = TodoList(
todos=[
Todo("学习Go语言", True),
Todo("完成设计模式作业", False),
Todo("锻炼身体", False),
]
)
# 创建迭代器
iterator = todo_list.CreateIterator()
# 使用迭代器遍历TODO表
item = iterator.First()
while not iterator.isDone():
done = "已完成" if item and item.done else "未完成"
print(
f"当前第 {iterator.CurrentItem()} 项任务内容: {item.content if item else ''} 是否完成: {done}"
)
item = iterator.Next()
print("\n=========== 迭代器模式结束 ===========")

92
ts/src/iterator/index.ts Normal file
View File

@ -0,0 +1,92 @@
/*
TODO表
*/
// 任务结构体 - 迭代器元素
interface Todo {
content: string;
done: boolean;
}
// 迭代器接口
interface IIterator {
First(): Todo;
Next(): Todo;
isDone(): boolean;
CurrentItem(): number;
}
// 具体迭代器 - 汤宝宝的TODO表迭代器
class TodoListIterator implements IIterator {
todoList: TodoList;
current: number;
constructor(todoList: TodoList) {
this.todoList = todoList;
this.current = 0;
}
First(): Todo {
this.current = 0;
return this.todoList.todos[this.current];
}
Next(): Todo {
this.current += 1;
return this.todoList.todos[this.current];
}
isDone(): boolean {
return this.current >= this.todoList.todos.length;
}
CurrentItem(): number {
if (this.current < 0 || this.current >= this.todoList.todos.length) {
return this.todoList.todos.length;
}
return this.current + 1;
}
}
// 集合接口
interface ICollection {
createIterator(): IIterator;
}
// 具体集合 - 汤宝宝的TODO表
class TodoList implements ICollection {
todos: Todo[];
constructor(todos: Todo[]) {
this.todos = todos;
}
createIterator(): IIterator {
return new TodoListIterator(this);
}
}
(function () {
console.log("============= 迭代器模式 =============");
// 创建TODO表并添加任务
const todoList = new TodoList([
{ content: "学习Go语言", done: true },
{ content: "完成设计模式作业", done: false },
{ content: "锻炼身体", done: false },
]);
// 创建迭代器
const iterator = todoList.createIterator();
// 使用迭代器遍历TODO表
for (
let item = iterator.First();
!iterator.isDone();
item = iterator.Next()
) {
console.log(
`当前第 ${iterator.CurrentItem()} 项任务内容: ${
item ? item.content : ""
} 是否完成: ${item && item.done ? "已完成" : "未完成"}`
);
}
console.log("\n=========== 迭代器模式结束 ===========");
})();