需求
设计一个公交车上售票员要求每个人买票的程序。
实现
abstract class Iterator { //第一个 public abstract Object first(); //下一个 public abstract Object next(); //时候到结尾 public abstract boolean isDone(); //当前对象 public abstract Object currentItem(); }
abstract class Aggregate { public abstract Iterator createIterator(); }
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() { Object ret=null; current++; if(current<aggregate.count()) { ret=aggregate.get(current); } return ret; } @Override public Object currentItem() { return aggregate.get(current); } @Override public boolean isDone() { return current>=aggregate.count()?true:false; } }
import java.util.*; class ConcreteAggregate extends Aggregate { private List<Object> items=new ArrayList<Object>(); @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 set(Object value) { items.add(value); } }
public class Main { public static void main(String[] args) { ConcreteAggregate a=new ConcreteAggregate(); a.set("大鸟"); a.set("小菜"); a.set("行李"); a.set("老外"); a.set("公交内部员工"); a.set("小偷"); Iterator iterator=new ConcreteIterator(a); while (!iterator.isDone()) { System.out.println(iterator.currentItem() + "\t请买车票."); iterator.next(); } } }迭代器模式,又叫做游标模式,提供一种方法访问一个容器对象中各个元素,而又不需暴露该对象的内部细节。
import java.util.*; public class Main { public static void main(String[] args) { List<Integer> list=new ArrayList<Integer>(); Random random=new Random(); for(int i=0;i<10;i++) { list.add(random.nextInt(20)); } System.out.println("数组元素:"+list); System.out.println("迭代结果:"); Iterator<Integer> iterator=list.iterator(); while(iterator.hasNext()) { System.out.print(iterator.next()+" "); } } }