设计模式(迭代器模式)
时间: 2023-11-13 13:03:47 浏览: 67
迭代器模式是一种行为设计模式,它提供了一种方法来访问一个容器对象中的各个元素,而不需要暴露该对象的内部细节。迭代器模式通过提供一个迭代器来实现这一点,该迭代器用于遍历容器中的元素。迭代器模式在Java Collection Framework中得到了广泛使用,其中Iterator接口提供了遍历集合的方法。
迭代器模式的主要优点是它提供了一种简单的方法来遍历一个容器对象中的元素,而不需要暴露该对象的内部细节。此外,迭代器模式还可以提供不同种类的迭代器,以满足不同的需求。
下面是一个迭代器模式的示例代码:
```python
class Iterator:
def __init__(self, collection):
self._collection = collection
self._index = 0
def __next__(self):
if self._index < len(self._collection):
item = self._collection[self._index]
self._index += 1
return item
else:
raise StopIteration
class Collection:
def __init__(self):
self._items = []
def add_item(self, item):
self._items.append(item)
def __iter__(self):
return Iterator(self._items)
# 使用示例
collection = Collection()
collection.add_item("Item 1")
collection.add_item("Item 2")
collection.add_item("Item 3")
for item in collection:
print(item)
```
输出结果为:
```
Item 1
Item 2
Item 3
```