↓でGoFイテレータパターンから各インターフェースを除外し、コンパイルが通るようにしました。しかしこの状態でも、ここから集約役割(本棚)の実装が変わっても(ex.配列→ArrayList)正常に動いてしまいます。
なのでインターフェースいらないじゃんって思ってしまったのですが、オブジェクト指向設計においては必要なのですよね?その理由を教えて下さい。
//メイン public class Main { public static void main(String[] args) { BookShelf bookShelf = new BookShelf(4); bookShelf.appendBook(new Book("Around the World in 80 Days")); bookShelf.appendBook(new Book("Bible")); bookShelf.appendBook(new Book("Cinderella")); bookShelf.appendBook(new Book("Daddy-Long-Legs")); //Iterator it = bookShelf.iterator(); BookShelfIterator it = bookShelf.iterator(); while (it.hasNext()) { Book book = (Book)it.next(); System.out.println(book.getName()); } } }
//数えるモノ(書籍) public class Book { private String name; public Book(String name) { this.name = name; } public String getName() { return name; } }
//集約役割(本棚) //public class BookShelf implements Aggregate { public class BookShelf { private Book[] books; private int last = 0; public BookShelf(int maxsize) { this.books = new Book[maxsize]; } public Book getBookAt(int index) { return books[index]; } public void appendBook(Book book) { this.books[last] = book; last++; } public int getLength() { return last; } // public Iterator iterator() { public BookShelfIterator iterator() { return new BookShelfIterator(this); } }
//イテレータ役割 //public class BookShelfIterator implements Iterator { public class BookShelfIterator { private BookShelf bookShelf; private int index; public BookShelfIterator(BookShelf bookShelf) { this.bookShelf = bookShelf; this.index = 0; } public boolean hasNext() { if (index < bookShelf.getLength()) { return true; } else { return false; } } public Object next() { Book book = bookShelf.getBookAt(index); index++; return book; } }
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/02/09 03:34