Java設計模式菜鳥系列(十一)迭代器模式建模與實現

來源:互聯網
上載者:User

標籤:容器   void   code   bottom   oid   add   his   text   water   

轉載請註明出處:http://blog.csdn.net/lhy_ycu/article/details/39807741


迭代器模式(Iterator):提供了一種方法順序訪問一個彙總對象中的各個元素,而又不暴露其內部的表示。

一、uml建模:



二、代碼實現

/** * 示範範例:迭代器模式 *  */interface Iterator {/** 前移 */public Object previous();/** 後移 */public Object next();/** 推斷是否有下一個元素 */public boolean hasNext();}interface Collection {public Iterator iterator();/** 取得集合中的某個元素 */public Object get(int i);/** 取得集合大小 */public int size();}/** * 集合 */class MyCollection implements Collection {private String[] strArray = { "aa", "bb", "cc", "dd" };@Overridepublic Iterator iterator() {return new MyIterator(this);}@Overridepublic Object get(int i) {return strArray[i];}@Overridepublic int size() {return strArray.length;}}/** * 迭代器 */class MyIterator implements Iterator {private Collection collection;private int pos = -1;public MyIterator(Collection collection) {this.collection = collection;}@Overridepublic Object previous() {if (pos > 0) {pos--;}return collection.get(pos);}@Overridepublic Object next() {if (pos < collection.size() - 1) {pos++;}return collection.get(pos);}@Overridepublic boolean hasNext() {if (pos < collection.size() - 1) {return true;}return false;}}/** * client測試類 *  * @author Leo */public class Test {public static void main(String[] args) {/** * 執行個體化容器 */Collection collection = new MyCollection();/** * 建立迭代器 */Iterator iterator = collection.iterator();/** * 遍曆集合中的元素 */while (iterator.hasNext()) {System.out.println(iterator.next());}}}

三、應用情境

遍曆、訪問集合中的某個元素等


四、總結

迭代器模式就是順序訪問集合中的對象,這句話包括兩層意思:一是須要遍曆的對象。即集合對象。二是迭代器對象,用於對集合對象進行遍曆訪問。


Java設計模式菜鳥系列(十一)迭代器模式建模與實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.