ConcreteAggregate(HaierTV):具體聚合實現(xiàn)創(chuàng)建相應(yīng)迭代器的接口,該操作返回ConcreteIterator的一個適當?shù)膶嵗?/font>
協(xié)作關(guān)系:ConcreteIterator跟蹤聚合中的當前對象,并能夠計算出待遍歷的后繼對象。
使用迭代器的好處:
1. 他支持以不同的方式遍歷一個聚合, 復(fù)雜的聚合可用多種方式進行遍歷。
2. 迭代器簡化了聚合的接口 有了迭代器的遍歷接口,聚合本身就不需要類似的遍歷接口了,這樣就簡化了聚合的接口。
3. 在同一個聚合上可以有多個遍歷 每個迭代器保持它自己的遍歷狀態(tài)。因此你可以同時進行多個遍歷。
在本例子中,Television定義了一個返回各個頻道列表的接口,這實際上是一個工廠方法,只是生產(chǎn)出來的產(chǎn)品所屬的類型支持Iterator的操作。
具體的代碼如下所示:
Iterator接口:
package iterator;
public interface Iterator{
public Item first();
public Item next();
public boolean isDone();
public Item currentItem();
}
Controller類實現(xiàn)了Iterator接口。
package iterator;
import java.util.Vector;
public class Controller implements Iterator{
private int current =0;
Vector channel;
public Controller(Vector v){
channel = v;
}
public Item first(){
current = 0;
return (Item)channel.get(current);
}
public Item next(){
current ++;
return (Item)channel.get(current);
}
public Item currentItem(){
return (Item)channel.get(current);
}
public boolean isDone(){
return current>= channel.size()-1;
}
}
Television接口:
package iterator;
import java.util.Vector;
public interface Television{
public Iterator createIterator();
public Vector getChannel();
}
HaierTV類實現(xiàn)了Television接口。
package iterator;
import java.util.Vector;
public class HaierTV implements Television{
private Vector channel;
public HaierTV(){
channel = new Vector();
channel.addElement(new Item("channel 1"));
channel.addElement(new Item("channel 2"));
channel.addElement(new Item("channel 3"));
channel.addElement(new Item("channel 4"));
channel.addElement(new Item("channel 5"));
channel.addElement(new Item("channel 6"));
channel.addElement(new Item("channel 7"));
}
public Vector getChannel(){
return channel;
}
public Iterator createIterator(){
return new Controller(channel);
}
}
Client客戶端:
package iterator;
public class Client{
public static void main(String[] args){
Television tv = new HaierTV();
Iterator it =tv.createIterator();
System.out.println(it.first().getName());
while(!it.isDone()){
System.out.println(it.next().getName());
}
}
}
Item類的接口:
package iterator;
public class Item{
private String name;
public Item(String aName){
name = aName;
}
public String getName(){
return name;
}
}
總結(jié):Iterator模式提供了一個訪問聚合數(shù)據(jù)的簡單思路,并支持多個迭代器同時訪問。