23种设计模式之迭代器模式
迭代器模式(Iterator):提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。
package designMode.iterator; interface Aggregate { Iterator createIterator(); }
package designMode.iterator; interface Iterator { Object first(); Object next(); boolean isDone(); Object currentItem(); }
package designMode.iterator; import java.util.ArrayList; import java.util.List; class ConcreteAggregate implements Aggregate{ private List<Object> items = new ArrayList<Object>(); @Override public Iterator createIterator() { return new ConcreteIterator(this); } public int count(){ return items.size(); } public Object getCurrent(int index){ return items.get(index); } public void setCurrent(int index,Object value){ items.add(index, value); } }
package designMode.iterator; class ConcreteIterator implements Iterator{ private ConcreteAggregate aggregate; private int current; public ConcreteIterator(ConcreteAggregate aggregate) { this.aggregate = aggregate; } @Override public Object first() { return aggregate.getCurrent(0); } @Override public Object next() { Object ret = null; current++; if(current<aggregate.count()) ret = aggregate.getCurrent(current); return ret; } @Override public boolean isDone() { return current>=aggregate.count()?true:false; } @Override public Object currentItem() { return aggregate.getCurrent(current); } }
package designMode.iterator; class Test { public static void main(String[] args) { ConcreteAggregate a = new ConcreteAggregate(); a.setCurrent(0, "张三"); a.setCurrent(1, "李四"); a.setCurrent(2, "王五"); a.setCurrent(3, "马六"); a.setCurrent(4, "田七"); a.setCurrent(5, "茅八"); Iterator iter = new ConcreteIterator(a); Object firstItem = iter.first(); System.out.println("第一个是:"+firstItem); while(!iter.isDone()){ System.out.println(iter.currentItem()+"已通过!"); iter.next(); } } }