生活随笔
收集整理的這篇文章主要介紹了
设计模式(第十七式:迭代器模式)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
概念: 迭代器模式:Provide a way to access the elements of an aggregarte object sequentiaally with exposing its underlying representation. 提供一種訪問容器對象內每個元素的一種方式,并且不暴露對象的一些內部細節。 實現: 迭代器接口定義
public interface Iterator {Object next();Boolean hasNext();
} 容器接口定義
public interface Box { void add(Object object);Iterator createIterator();
} 迭代器實現
public class BoxIterator
implements Iterator { private BookBox bookBox; private Integer size; private Integer index; public BoxIterator(BookBox bookBox){ this .bookBox =
bookBox; this .size =
bookBox.size(); this .index = 0
;}@Override public Object next() { if (index<
size){ return bookBox.getElement(index++
);} return null ;}@Override public Boolean hasNext() { return index<
size;}
} 容器實現
public class BookBox
implements Box { private Vector vector =
new Vector();@Override public void add(Object object) { this .vector.add(object);} public Object getElement(Integer index){ if (index<
vector.size()){ return vector.get(index);} return null ;} public Integer size(){ return vector.size();}@Override public Iterator createIterator() { return new BoxIterator(
this );}
} 測試及結果:
@Test
public void iteratorTest() {BookBox bookBox =
new BookBox();bookBox.add( "歷史書"
);bookBox.add( "政治書"
);bookBox.add( "語文書"
);bookBox.add( "數學書"
);bookBox.add( "英語書"
);Iterator iterator =
bookBox.createIterator(); while (iterator.hasNext()) {System.out.println(iterator.next());}
} 歷史書 政治書 語文書 數學書 英語書 分析: 1.簡化了對容器的遍歷操作,直接提供了遍歷接口 2.最常用的就是jdk的集合迭代器,這個迭代器接口是在1.2版本加入的。
轉載于:https://www.cnblogs.com/ben-mario/p/11133536.html
總結
以上是生活随笔 為你收集整理的设计模式(第十七式:迭代器模式) 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。