Iterator模式
# 迭代器模式 class Aggregate: """aggregate类""" def iterator(self): pass class Iterator: """Iterator类""" def has_next(self): pass def next(self): pass class Book: """书本类""" def __init__(self, name): self.name = name def get_name(self): return self.name class BookIterator(Iterator): """具体迭代器""" def __init__(self, shelf): self.shelf = shelf self.index = 0 def has_next(self): if self.index < self.shelf.get_length(): return True else: return False def next(self): book = self.shelf.get_book_at(self.index) self.index += 1 return book class BookShelf(Aggregate): """书架类, 具体aggregate""" def __init__(self, max_size): self.book_list = [] self.max_size = max_size self.last = 0 def append_book(self, book): """添加书""" if self.get_length() < self.max_size: self.book_list.append(book) self.last += 1 def get_book_at(self, index): """获取指定位置的书""" return self.book_list[index] def get_length(self): """获取当前书本数""" return self.last def iterator(self): return BookIterator(self) if __name__ == '__main__': book_a = Book('红楼梦') book_b = Book('水浒传') book_c = Book('三国演义') book_d = Book('西游记') book_shelf = BookShelf(4) book_shelf.append_book(book_a) book_shelf.append_book(book_b) book_shelf.append_book(book_c) book_shelf.append_book(book_d) it = book_shelf.iterator() while it.has_next(): book_obj = it.next() print(book_obj.get_name())
迭代器模式让你在不暴露集合底层实现形式的情况下遍历集合中的所有元素。
迭代器模式有四个角色:集合,具体的集合,迭代器,具体的迭代器。 集合和迭代器是抽象类,具体的集合和集体的迭代器是实现了集合和迭代器的类。
将遍历功能置于集合角色之外是迭代器模式的一个特征。
在这里的代码中,遍历的代码并不依赖于book_shelf的代码实现,这样无论book_shelf的has_next()和next()方法怎么变,遍历的调用方式都不用改变。