国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Iterator ------迭代器

2019-11-08 19:51:58
字體:
來源:轉載
供稿:網友

Iterator ——迭代器

程序示例

Aggregate 接口

// 建立一個可對應聚合的iteratorpublic interface Aggregate { public Iterator Iterator();}

Iterator 接口

public interface Iterator { public boolean hasNext(); public Object next();}

Book 類

public class Book { PRivate String name = ""; public Book(String name) { this.name = name; } public String getName() { return name; }}

BookShelf 類

public class BookShelf implements Aggregate { 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() { return new BookShelfIterator(this); }}

BookShelfIterator 類

public class BookShelfIterator implements Iterator { 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; }}

Main 類

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 iterator = bookShelf.iterator(); while (iterator.hasNext()) { Book book = (Book)iterator.next(); System.out.println("" + book.getName()); } }}

Iterator Pattern 的所有參與者

Iterator(迭代器) 參與者ConcreteIterator(具體迭代器) 參與者Aggregate(聚合) 參與者ConcreteAggregate(具體聚合) 參與者

擴展自我視野的提示

無論實現結果如何,都能使用Iterator

設計Pattern的目的就是為了提高類的復用率。提高復用率則是指吧類當作一個零件來使用,只要修改某一個零件,就不需要大費周章去修改其他的零件。

抽象類、接口實在很難搞

過度依賴具體類反而會提高類與類的耦合度,增加零部件復用的困難。為了降低耦合度,讓類作為零部件再利用,必須引進抽象類和接口的概念。

“下一個”容易搞錯

返回現在的元素,同時進行到下一個位置。

練習題

問題1

若書籍數量超過最先設定的書架大小,就無法繼續把書放上去。請利用java.util.Vector取代數組,把程序改成即使已經超過書架容量也能繼續新增書籍。

答案

import java.util.Vector;public class BookShelf implements Aggregate { private Vector books; public BookShelf(int initialsize) { this.books = new Vector(initialsize); } public Book getBookAt(int index) { return (Book)books.get(index); } public void appendBook(Book book) { books.add(book); } public int getLength() { return books.length; } public Iterator iterator() { return new BookShelfIterator(this); }}
上一篇:專題七-樹

下一篇:泛型接口和方法

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 锡林郭勒盟| 台东市| 铜陵市| 肇州县| 固始县| 固镇县| 古蔺县| 肥乡县| 阿拉善盟| 普宁市| 邯郸市| 西乡县| 昌平区| 新绛县| 搜索| 迭部县| 翁源县| 诸暨市| 台北县| 德安县| 黑河市| 叙永县| 镇巴县| 阳原县| 宜兰县| 芷江| 高碑店市| 铜川市| 瑞丽市| 崇信县| 稷山县| 青龙| 祁东县| 巩义市| 龙井市| 河东区| 探索| 东宁县| 霸州市| 苏尼特右旗| 新邵县|