1
0
Fork 0
design-patterns/python/iterator/main.py

106 lines
2.4 KiB
Python
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.

"""
实例:
汤宝宝有一张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=========== 迭代器模式结束 ===========")