1
2

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 3 years have passed since last update.

TypeScriptでデザインパターン[1.Iterator]

Last updated at Posted at 2021-03-14

はじめに

Typescriptでデザインパターンをやっていくシリーズ(にする予定です)

結城 浩さんの「Java言語で学ぶデザインパターン入門」をTSに置き換えてTS力をあげていこうという趣旨です。

メモ

Iteratorかぶり

TSには元々IteratorというInterfaceが予約されていたので、MyInterfaceというクラス名に変更した。
TSのIteratorを使って実装してみるのも面白いかもしれない
https://typescript-jp.gitbook.io/deep-dive/future-javascript/iterators

反省

  • lastというパラメータはいらなかった。books.lengthでよかった。

Code

interface MyIterator {
  hasNext(): boolean;
  next(): Object;
}
interface Aggregate {
  iterator(): MyIterator;
}

class Book {
  private name: string;

  constructor(name: string) {
    this.name = name;
  }

  getName(): string {
    return this.name;
  }
}

class BookShelf implements Aggregate {
  private books: Book[];
  private last: number = 0;
  constructor() {
    this.books = [];
  }

  getBookAt(index: number): Book {
    return this.books[index];
  }

  appendBook(book: Book) {
    this.books[this.last] = book;
    this.last++;
  }
  getLength(): number {
    return this.last;
  }
  iterator() {
    return new BookShelfIterator(this);
  }
}

class BookShelfIterator implements MyIterator {
  private bookShelf: BookShelf;
  private index: number;

  constructor(bookShelf: BookShelf) {
    this.bookShelf = bookShelf;
    this.index = 0;
  }

  hasNext(): boolean {
    if (this.index < this.bookShelf.getLength()) {
      return true;
    }
    return false;
  }

  next(): Book {
    const book = this.bookShelf.getBookAt(this.index);
    this.index++;
    return book;
  }
}

class Main {
  main() {
    const bookShelf = new BookShelf();
    bookShelf.appendBook(new Book("Alpha"));
    bookShelf.appendBook(new Book("Barvo"));
    bookShelf.appendBook(new Book("Charlie"));
    bookShelf.appendBook(new Book("Delta"));
    const iterator = bookShelf.iterator();

    while (iterator.hasNext()) {
      console.log(iterator.next().getName());
    }
  }
}

const main = new Main();
main.main();

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?