0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

iterator pattern

ケース

集約オブジェクトの内部構造を知ることなくアクセスできるようにしたいとき

結果

pro

アクセス方法を局所化できる
複数のアクセス方法を容易に提供できる
同時に複数からアクセスできうる

con

ない

実装対象

集約インターフェイス
集約クラス
Iteratorインターフェイス
Iterator class

種類

内部イテレーターと外部イテレーターがある。

クライアントがイテレーションを制御する -> 外部イテレーター

while let element = iterator.next {
    // do something
}

Iteratorがイテレーションを制御する -> 内部イテレーター

iterator.traverse()

example

protocol AggregateProtocol {
    associatedtype Item
    func createIterator() -> IteratorProtocol
    func get(for index: Int) -> Item
    func count() -> Int
}

protocol IteratorProtocol {
    associatedtype Item
    var next: Item? { get }
}

class Apartment: AggregateProtocol {
    typealias Item = Room
    private let rooms: [Room]

    func createIterator() -> IteratorProtocol {
        return RoomIterator()
    }

    func get(for index: Int) {
        return rooms[index] // TODO: care out of range
    }

    func count() -> Int { return rooms.count }
}

class RoomIterator: IteratorProtocol {
    typealias Item = Room
    private let index: Int = 0
    private let apartment: Apartment

    var next: Room? {
        let room = apartment.get(for: index)
        index += 1
        return room
    }
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?