提供一种方法访问一个容器对象中各个元素,而又不需暴露该对象的内部细节。
迭代器模式属于行为型模式。
迭代器(Iterator)模式,又叫做游标(Cursor)模式。
Java中的Map、List等容器,都使用到了迭代器模式。

角色声明
Iterator(迭代器接口):负责定义、访问和遍历元素的接口。
ConcreteIterator(具体迭代器类):实现迭代器接口。
Aggregate(容器接口):定义容器的基本功能以及提供创建迭代器的接口。
ConcreteAggregate(具体容器类):实现容器接口中的功能。
Client(客户端类):即要使用迭代器模式的地方
//迭代器接口public interface IteratorInterface {//是否存在下一条记录boolean hasNext();//返回当前对象并移动到下一条记录Object next();}//创建容器的基本属性//容器用于迭代public interface Aggregate {//容器大小int size();//获取源苏String get(int index);//添加人名void add(String userName);//移除源苏void remove(int index);//返回迭代器对象IteratorInterface iterator();}//迭代器的具体实现类public class AggreateImpl implements IteratorInterface {private Aggregate aggregate;//返回当前索引private int index;public AggreateImpl(Aggregate ag){this.aggregate=ag;}@Overridepublic boolean hasNext() {//如果索引小于容器大小 那么return trueif (index < aggregate.size()) {return true;} else {return false;}}@Overridepublic Object next() {//返回对象并让对象的索引+1return aggregate.get(index++);}}public class DeliveryAggregate implements Aggregate {private List <String> list = new LinkedList <>();// 容器大小public int size() {return list.size();}public String get(int location) {return list.get( location );}public void add(String tel) {list.add( tel );}@Overridepublic void remove(int index) {list.remove( index );}@Overridepublic IteratorInterface iterator() {return new AggreateImpl( this );}}public class AggreateClient {public static void main(String[] args) {Aggregate aggregate = new DeliveryAggregate();aggregate.add("1111");aggregate.add("2222");aggregate.add("3333");aggregate.add("9527");IteratorInterface iterator = aggregate.iterator();while (iterator.hasNext()) {String tel = (String) iterator.next();System.out.println("当前号码为:" + tel);}System.out.println("后面没有了");}}
