参考:https://blog.csdn.net/zhengzhb/article/details/7610745
例子:
# 抽象迭代器
class Iterator:
def has_next(self) -> bool:
raise NotImplementedError("Must subclass me!")
def first(self) -> object:
raise NotImplementedError("Must subclass me!")
def next(self) -> object:
raise NotImplementedError("Must subclass me!")
# 具体迭代器
class ConcreteIterator(Iterator):
def __init__(self):
self.container = []
self.cursor = 0
def has_next(self) -> bool:
return True if self.cursor < len(self.container) else False
def first(self) -> object:
if len(self.container) >= 0:
return self.container[0]
def next(self) -> object:
if self.has_next():
current_element = self.container[self.cursor]
self.cursor += 1
return current_element
return None
# 抽象容器
class Container:
def iterator(self) -> Iterator:
raise NotImplementedError("Must subclass me!")
def add(self, element) -> None:
raise NotImplementedError("Must subclass me!")
def remove(self, element) -> None:
raise NotImplementedError("Must subclass me!")
# 具体容器
class ConcreteContainer(Container):
def __init__(self):
self.it = self.iterator()
def iterator(self) -> Iterator:
return ConcreteIterator()
def add(self, element) -> None:
self.it.container.append(element)
def remove(self, element) -> None:
self.it.container.remove(element)
# 测试
if __name__ == '__main__':
mycontainer = ConcreteContainer()
mycontainer.add("xixi")
mycontainer.add("haha")
mycontainer.add("hehe")
mycontainer.add("hihi")
mycontainer.add("wuwu")
mycontainer.add("wawa")
myiter = mycontainer.it # 获取容器的迭代器
while myiter.has_next():
print(myiter.next())