Swiftで書く「Java言語で学ぶデザインパターン入門 第3版」第1章 Iterator

Java言語で学ぶデザインパターン入門 第3版

サンプルプログラムをSwiftで書く。

第1章 Iterator

Bookクラス

import Foundation

public class Book {
    private var name: String
    
    public init(name: String) {
        self.name = name
    }
    
    public func getName() -> String {
        return self.name
    }
}

BookShelfクラス

import Foundation

public class BookShelf: Sequence {
    private var books: [Book] = []

    public func getBookAt(index: Int) -> Book {
        return self.books[index]
    }

    public func appendBook(book: Book) {
        self.books.append(book)
    }
    
    public func getLength() -> Int {
        self.books.count
    }
    
    public func makeIterator() -> some IteratorProtocol {
        return BookShelfIterator(self)
    }
}

BookShelfIteratorクラス

import Foundation

public class BookShelfIterator: IteratorProtocol {
    public typealias Element = Book
    
    var index: Int
    
    private let bookShelf: BookShelf
    
    public init(_ bookShelf: BookShelf) {
        self.bookShelf = bookShelf
        self.index = 0
    }
        
    public func next() -> Element? {
        guard index < self.bookShelf.getLength() else {
            return nil
        }
        let book = self.bookShelf.getBookAt(index: index)
        index = index + 1
        return book
    }
}

Mainクラス

import Foundation

public class DP01Iterator {
    public static func main() {
        let bookShelf: BookShelf = BookShelf()
        bookShelf.appendBook(book: Book(name: "Around the world in 80 Days"))
        bookShelf.appendBook(book: Book(name: "Bible"))
        bookShelf.appendBook(book: Book(name: "Cinderella"))
        bookShelf.appendBook(book: Book(name: "Daddy-Long-Legs"))

        var it = bookShelf.makeIterator()
        while let book = it.next() as? Book {
            print(book.getName())
        }        
    }
}

main.swift

import Foundation

DP01Iterator.main()

Swift

Posted by shi-n