迭代器模式
一、定义
提供一种方式顺序地访问一个聚合对象中的各个元素,而又不暴露此对象的内部表示。
二、类图表示
三、实现
1、Aggregate
package pattern.behavioral.iterator;
public abstract class Aggregate {
public abstract Iterator createIterator();
}
package pattern.behavioral.iterator;
import java.util.ArrayList;
import java.util.List;
public class ConcreteAggregate extends Aggregate {
private List<Object> items = new ArrayList<>();
@Override
public Iterator createIterator() {
return new ConcreteIterator(this);
}
public int count(){
return items.size();
}
public Object get(int index){
return items.get(index);
}
public void add(int index, Object element){
items.add(index, element);
}
}
2、Iterator
package pattern.behavioral.iterator;
public abstract class Iterator {
public abstract Object first();
public abstract Object next();
public abstract boolean isDone();
public abstract Object currentItem();
}
package pattern.behavioral.iterator;
public class ConcreteIterator extends Iterator {
private ConcreteAggregate aggregate;
private int current = 0;
public ConcreteIterator(ConcreteAggregate aggregate) {
this.aggregate = aggregate;
}
@Override
public Object first() {
return aggregate.get(0);
}
@Override
public Object next() {
if(current < aggregate.count() - 1){
return aggregate.get(++current);
}
return null;
}
@Override
public boolean isDone() {
return current >= aggregate.count();
}
@Override
public Object currentItem() {
return aggregate.get(current);
}
}
四、使用
package pattern.behavioral.iterator;
public class Client {
public static void main(String[] args) {
ConcreteAggregate aggregate = new ConcreteAggregate();
aggregate.add(0, "ItemA");
aggregate.add(1, "ItemB");
aggregate.add(2, "ItemC");
aggregate.add(3, "ItemD");
ConcreteIterator iterator = new ConcreteIterator(aggregate);
System.out.println("The first element is :" + iterator.first());
while(iterator.next() != null){
System.out.println(iterator.currentItem());
}
}
}
- 程序输出:
The first element is :ItemA
ItemB
ItemC
ItemD
五、适用场合
-
访问一个聚合对象的内容而无需暴露其内部表示
-
支持对聚合对象的多种遍历
-
为遍历不同的聚合结构提供统一的接口