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

This commit is contained in:
2026-01-06 02:03:46 +08:00
parent cc215c9d70
commit f579b1a5cc
3 changed files with 298 additions and 0 deletions
+105
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=========== 迭代器模式结束 ===========")