...

Python设计模式-20-迭代器模式

迭代器模式是一种行为型设计模式,它允许我们按照顺序访问一个聚合对象中的元素,而不需要暴露该对象的内部表示。迭代器模式通常包括以下几个角色:

  • 迭代器(Iterator):定义了一个接口,用于按照顺序访问聚合对象中的元素。

  • 具体迭代器(Concrete Iterator):实现了迭代器定义的接口,并维护了当前迭代位置。

  • 聚合对象(Aggregate):定义了一个接口,用于创建迭代器对象。

  • 具体聚合对象(Concrete Aggregate):实现了聚合对象定义的接口,并返回一个具体迭代器对象。

下面是一个简单的 Python 示例,演示了如何使用迭代器模式:


class Iterator:
    def has_next(self):
        pass

    def next(self):
        pass

class ConcreteIterator(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():
            item = self.collection[self.index]
            self.index += 1
            return item
        else:
            return None

class Aggregate:
    def create_iterator(self):
        pass

class ConcreteAggregate(Aggregate):
    def __init__(self):
        self.collection = []

    def add_item(self, item):
        self.collection.append(item)

    def create_iterator(self):
        return ConcreteIterator(self.collection)

aggregate = ConcreteAggregate()
aggregate.add_item('Item 1')
aggregate.add_item('Item 2')
aggregate.add_item('Item 3')

iterator = aggregate.create_iterator()
while iterator.has_next():
    item = iterator.next()
    print(item)
	```

在上面的示例中,我们定义了一个迭代器 `Iterator`,它定义了一个接口 `has_next()` 和 `next()`,用于按照顺序访问聚合对象中的元素。然后,我们定义了一个具体迭代器 `ConcreteIterator`,它实现了迭代器定义的接口,并维护了当前迭代位置。接下来,我们定义了一个聚合对象 `Aggregate`,它定义了一个接口 `create_iterator()`,用于创建迭代器对象。然后,我们定义了一个具体聚合对象 `ConcreteAggregate`,它实现了聚合对象定义的接口,并返回一个具体迭代器对象。

在使用迭代器模式时,我们可以通过创建迭代器对象来按照顺序访问聚合对象中的元素,而不需要暴露该对象的内部表示。在上面的示例中,我们创建了一个具体聚合对象 `aggregate`,并将三个元素添加到其中。然后,我们创建了一个具体迭代器对象 `iterator`,并使用 `while` 循环按照顺序访问聚合对象中的元素。需要注意的是,迭代器模式可以帮助我们将聚合对象的遍历算法与其内部表示分离开来,从而提高代码的可维护性和可扩展性。
posted @ 2023-06-16 18:45  韩志超  阅读(93)  评论(0编辑  收藏  举报