适用场景
用于遍历容器,隐藏访问细节,为所有的容器提供统一的遍历接口。
类图
实例代码
我写了一个int的容器用来简单说明一下
Aggregate:
public interface Aggregate {
Iterator iterator();
int get(int index);
}
ConcreteAggregate:
public class ConcreteAggregate implements Aggregate{
int[] nums;
public ConcreteAggregate() {
nums=new int[10];
for(int i=0;i<10;i++)
nums[i]=i*i;
}
public int get(int index){
return nums[index];
}
@Override
public Iterator iterator() {
return new ConcreteIterator(this);
}
}
Iterator:
public interface Iterator {
boolean hasNext();
Object next();
}
ConcreteIterator
public class ConcreteIterator implements Iterator{
Aggregate aggregate;
int currIndex;
public ConcreteIterator(Aggregate aggregate) {
this.aggregate = aggregate;
currIndex=0;
}
@Override
public boolean hasNext() {
return (currIndex<10)?true:false;
}
@Override
public Object next() {
return aggregate.get(currIndex++);
}
}
Client:
public class Client {
public static void main(String[] args){
Aggregate aggregate=new ConcreteAggregate();
Iterator it=aggregate.iterator();
while(it.hasNext())
System.out.print(it.next()+"\t");
}
}

本文介绍了一种常用的设计模式——迭代器模式,并通过一个简单的int容器实现进行详细讲解。该模式能够为各种容器提供一致的访问接口,隐藏了容器内部的具体实现细节。
438

被折叠的 条评论
为什么被折叠?



