Edited at

Swiftでデザインパターン イテレーターパターン

More than 1 year has passed since last update.

こちらを参考に、Swiftで簡単に書き直し

https://qiita.com/sugihara-masaki/items/0d3982276eb7494dc25d


イテレーターパターン


  • コンテナの内部表現を隠蔽して要素へのアクセスを提供するパターン

  • 「リリース日が最近の順」など順番の項目ごとにIteraterクラスを作成し、そこで実装することで、関心を分離する


struct Movie {
var title: String
var publishedYear: Int = 0
}

struct MovieAggregate {
var movies: [Movie] = [Movie]()

mutating func addMovie(movie: Movie) {
self.movies.append(movie)
}

func getByIndex(index: Int) -> Movie {
return self.movies[index]
}

func size() -> Int {
return self.movies.count
}
}

struct RecentIterator {
var sortedMovies: [Movie] = [Movie]()
var index: Int = 0

init(aggregate: MovieAggregate) {
self.sortedMovies = aggregate.movies.sorted(by: {
$0.publishedYear > $1.publishedYear
})
self.index = 0
}

func hasNext() -> Bool {
return self.index < self.sortedMovies.count
}

mutating func nextItem() -> Movie {
let item = self.sortedMovies[index]
self.index = index + 1
return item
}
}

var movieAggregate = MovieAggregate()

let shawshank = Movie(title: "ショーシャンクの空に", publishedYear: 1994)
movieAggregate.addMovie(movie: shawshank)

let matrix = Movie(title: "マトリックス", publishedYear: 1999)
movieAggregate.addMovie(movie: matrix)

let outrage = Movie(title: "アウトレイジ", publishedYear: 2010)
movieAggregate.addMovie(movie: outrage)

var iterator = RecentIterator(aggregate: movieAggregate)

while iterator.hasNext() {
let movie = iterator.nextItem()
print(movie.title)
}