迭代器模式(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" };
@Override
public Iterator iterator() {
return new MyIterator(this);
}
@Override
public Object get(int i) {
return strArray[i];
}
@Override
public int size() {
return strArray.length;
}
}
/**
* 迭代器
*/
class MyIterator implements Iterator {
private Collection collection;
private int pos = -1;
public MyIterator(Collection collection) {
this.collection = collection;
}
@Override
public Object previous() {
if (pos > 0) {
pos--;
}
return collection.get(pos);
}
@Override
public Object next() {
if (pos < collection.size() - 1) {
pos++;
}
return collection.get(pos);
}
@Override
public boolean hasNext() {
if (pos < collection.size() - 1) {
return true;
}
return false;
}
}
/**
* 客戶端測試類
*
* @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設計模式博客全目錄