迭代子模式:可以顺序的访问一个聚集中的元素而不必暴露聚集的内部表象
迭代子模式:主动迭代子和被动迭代子,也分别叫做内部迭代子 和外部迭代子
抽线迭代子
package com.javapatterns.iterator.whitebox; public interface Iterator { void first(); void next(); boolean isDone(); Object currentItem(); }
具体迭代子:
package com.javapatterns.iterator.whitebox; public class ConcreteIterator implements Iterator { /** * @directed */ private ConcreteAggregate agg; private int index = 0; private int size = 0; public ConcreteIterator(ConcreteAggregate agg) { this.agg = agg; size = agg.size(); index = 0 ; } public void first() { index = 0 ; } public void next() { if (index < size) { index++; } } public boolean isDone() { return (index >= size); } public Object currentItem() { return agg.getElement(index); } }
抽象聚集:
package com.javapatterns.iterator.whitebox; abstract public class Aggregate { public Iterator createIterator() { return null; } }
具体聚集:
package com.javapatterns.iterator.whitebox; public class ConcreteAggregate extends Aggregate { private Object objs[]= {"Monk Tang", "Monkey", "Pigsy", "Sandy", "Horse"}; public Iterator createIterator() { return new ConcreteIterator(this); } public Object getElement(int index) { if (index < objs.length) { return objs[index]; } else { return null; } } public int size() { return objs.length; } }
客户端:
package com.javapatterns.iterator.whitebox; public class Client { /** * @directed */ private Iterator it; /** * @directed */ private Aggregate agg = new ConcreteAggregate(); public void operation() { it = agg.createIterator(); while (!it.isDone()) { System.out.println(it.currentItem().toString()); it.next(); } } public static void main(String[] args) { Client client = new Client(); client.operation(); } }