当您说迭代器模式,您指的是一个设计模式,它为遍历集合提供了一种统一的方式,同时隐藏了集合的内部结构。下面是一个在Python中实现迭代器模式的简单示例代码:
# 创建一个迭代器接口
class Iterator:
def __init__(self, collection):
self.collection = collection
self.index = 0
def has_next(self):
return self.index < len(self.collection)
def next(self):
if self.has_next():
value = self.collection[self.index]
self.index += 1
return value
else:
return None
# 创建一个可迭代的集合类
class Collection:
def __init__(self):
self.data = []
def add_item(self, item):
self.data.append(item)
def __iter__(self):
return Iterator(self.data)
# 使用示例
collection = Collection()
collection.add_item("Apple")
collection.add_item("Banana")
collection.add_item("Orange")
iterator = iter(collection)
while iterator.has_next():
item = iterator.next()
print(item)
以上代码演示了如何使用迭代器模式来遍历一个自定义的集合类。您可以根据需要更改集合的内部实现,而不会影响迭代器的使用方式。希望这个例子对您有所帮助!如果您有任何问题,请随时问我!