3
0

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.

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

Last updated at Posted at 2018-09-16

こちらを参考に、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)
}

3
0
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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?