一,概念
迭代器模式(Iterator Pattern)是 Java 和 .Net 编程环境中非常常用的设计模式。这种模式用于顺序访问集合对象的元素,不需要知道集合对象的底层表示。
迭代器模式属于行为型模式。
java配图,这里用swift来实现
二,使用场景:
- 访问一个聚合对象的内容而无须暴露它的内部表示。
- 需要为聚合对象提供多种遍历方式。
- 为遍历不同的聚合结构提供一个统一的接口。
三,代码演示
书:
struct Book { let name: String let author: String }
书的数组
struct BookList { let books: [Book] }
迭代器
struct BookListInterator : IteratorProtocol{ typealias Element = Book private var index = 0 private let bookList : [Element] init(books: [Element]) { self.bookList = books } mutating func next() -> Element? { defer { index += 1 } return bookList.count > index ? bookList[index] : nil } }
extension BookList: Sequence{ func makeIterator() -> BookListInterator { return BookListInterator(books: books) } }
客户端代码
class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let books = BookList(books: [Book(name: "西游记", author: "吴承恩"), Book(name: "三国演义", author: "罗贯中")]) for book in books { print("book name: \(book.name) author: \(book.author)") } } }