設計模式基礎 行為模式 - 7 - 迭代器(Iterator)__設計模式

來源:互聯網
上載者:User
1. 模式意圖

別名遊標(Cursor),提供一種方法順序訪問一個彙總對象中各個元素,而又不需要暴露該對象的內部對象。


這一模式的關鍵思想是將對列表/彙總的訪問和遍曆從彙總對象中分離出來並放入一個迭代器對象中。迭代器類定義一個訪問該彙總元素的介面。迭代器對象負責跟蹤當前的元素:即,它知道哪些元素已經遍曆過了。

將遍曆機制與彙總對象分離使我們可以定義不同的迭代器來實現不同的遍曆策略。


迭代器和彙總是耦合在一起的,而且客戶對象必須知道遍曆的彙總結構。最好能有一種辦法使得不需改變客戶代碼即可改變該彙總類。可以通過將迭代器的概念推廣到多態迭代來達到這個目標。


建立迭代器,要讓彙總對象負責建立相應的迭代器。客戶請求調用該操作以獲得一個迭代器對象。


在同一個彙總上可以有多個遍曆,每個迭代器保持它自己的遍曆狀態。因此,可以同時進行多個遍曆。


2. 模式定義



迭代器(Iterator):                            迭代器定義訪問和遍曆元素的介面。

具體迭代器(ConcreteIterator):  具體迭代器實現迭代器介面;對該彙總遍曆時跟蹤當前位置。

彙總(Aggregate):                          彙總定義建立相應迭代器對象的介面。

具體彙總(ConcreteAggregate):具體彙總實現建立相應迭代器的介面。


3. 模式實現 3.1 Java實現迭代器模式

interface Iterator {      public Object next();      public boolean hasNext();  }  class ConcreteIterator implements Iterator{      private List list = new ArrayList();      private int cursor =0;      public ConcreteIterator(List list){          this.list = list;      }      public boolean hasNext() {          if(cursor==list.size()){              return false;          }          return true;      }      public Object next() {          Object obj = null;          if(this.hasNext()){              obj = this.list.get(cursor++);          }          return obj;      }  }  interface Aggregate {      public void add(Object obj);      public void remove(Object obj);      public Iterator iterator();  }  class ConcreteAggregate implements Aggregate {      private List list = new ArrayList();      public void add(Object obj) {          list.add(obj);      }        public Iterator iterator() {          return new ConcreteIterator(list);      }        public void remove(Object obj) {          list.remove(obj);      }  }  public class Client {      public static void main(String[] args){          Aggregate ag = new ConcreteAggregate();          ag.add("1");          ag.add("2");          ag.add("3");          Iterator it = ag.iterator();          while(it.hasNext()){              String str = (String)it.next();              System.out.println(str);          }      }  }  


4. 模式應用





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.