模式定義
提供一種方法順序訪問一個聚合對象中的各種元素嗦明,而又不暴露該對象的內部表示库北。
模式結構
模式結構
Iterator:迭代器接口朴恳。定義訪問和遍歷元素的接口欺栗。
ConcreteIterator:具體的迭代器實現(xiàn)對象毫痕。實現(xiàn)對聚合對象的遍歷壳快,并跟蹤遍歷時的當前位置。
Aggregate:聚合對象镇草。定義創(chuàng)建相應迭代器對象的接口眶痰。
ConcreteAggregate:具體聚合對象。實現(xiàn)創(chuàng)建相應的迭代器對象梯啤。
代碼實現(xiàn)
public abstract class Aggregate {
public abstract Iterator CreateIterator();
}
class ConcreteAggregate extends Aggregate {
private String[] ss = null;
public ConcreteAggregate(String[] ss) {
this.ss = ss;
}
public Iterator CreateIterator() {
return new ConcreteIterator(this);
}
public Object get(int index) {
Object object = null;
if (index < ss.length) {
object = ss[index];
}
return object;
}
public int size() {
return this.ss.length;
}
}
public interface Iterator {
public void first();
public void next();
public Object currentItem();
public boolean idDone();
}
class ConcreteIterator implements Iterator {
private int index = -1;
private ConcreteAggregate aggregate;
public ConcreteIterator(ConcreteAggregate aggregate) {
this.aggregate = aggregate;
}
public void first() {
index = 0;
}
public void next() {
if (index < this.aggregate.size()) {
index = index + 1;
}
}
public Object currentItem() {
return this.aggregate.get(index);
}
public boolean idDone() {
if(index == this.aggregate.size()){
return true;
}
return false;
}
}
public class Client {
public static void main(String[] args) {
String[] names = {"1", "2", "3"};
Aggregate aggregate = new ConcreteAggregate(names);
Iterator iterator = aggregate.CreateIterator();
iterator.first();
while (!iterator.idDone()) {
Object obj = iterator.currentItem();
System.out.println(obj);
iterator.next();
}
}
}
模式的優(yōu)缺點
優(yōu)點
它支持以不同的方式遍歷一個聚合對象竖伯。
迭代器簡化了聚合類。
在同一個聚合上可以有多個遍歷因宇。
在迭代器模式中七婴,增加新的聚合類和迭代器類都很方便,無須修改原有代碼察滑。
缺點
由于迭代器模式將存儲數(shù)據(jù)和遍歷數(shù)據(jù)的職責分離打厘,增加新的聚合類需要對應增加新的迭代器類,類的個數(shù)成對增加贺辰,這在一定程度上增加了系統(tǒng)的復雜性户盯。
思考
模式本質:控制訪問聚合對象中的元素。
開發(fā)中的應用場景
訪問一個聚合對象的內容而無須暴露它的內部表示饲化。
需要為聚合對象提供多種遍歷方式莽鸭。
為遍歷不同的聚合結構提供一個統(tǒng)一的接口。