package liu.iterator.demo;
public abstract class Iterator {
public abstract Object First();
public abstract Object Next(); public abstract Boolean IsDone(); public abstract Object CurrentItem(); } --------------------------------------- package liu.iterator.demo;
public class ConcreteIterator extends Iterator{
private int current = 0;
private ConcreteAggregate aggregate; public ConcreteIterator(ConcreteAggregate aggregate){ this.aggregate = aggregate; } @Override public Object First() { return aggregate.getElement(0); }
@Override
public Object Next() { Object ret = null; current++; if(current < aggregate.Count()){ ret = aggregate.getElement(current); } return ret; }
@Override
public Boolean IsDone() { return current>=aggregate.Count()?true:false; }
@Override
public Object CurrentItem() { return aggregate.getElement(current); }
}
----------------------------------------- package liu.iterator.demo;
public abstract class Aggregate {
public abstract Iterator CreateIterator(); } ------------------------------------------ package liu.iterator.demo;
import java.util.ArrayList;
import java.util.List;
public class ConcreteAggregate extends Aggregate{
private List<Object> items = new ArrayList<Object>();
Object[] present = {"大鸟","小鸟","行李","小鸟","行李","小鸟","行李"}; @Override public Iterator CreateIterator() { return new ConcreteIterator(this); } public int Count(){ return present.length; } public Object getElement(int index){ //得到当前乘客的情况 if(index<present.length){ return present[index]; } else{ return null; } }
}
------------------------------------------ package liu.iterator.demo;
public class Main {
private Iterator it;
private Aggregate a = new ConcreteAggregate(); public void operation(){ it = a.CreateIterator(); //售票员开始点名 while(!it.IsDone()){ //如果没点完 System.out.println(it.CurrentItem().toString()); //获得被点到乘客的情况 it.Next(); //点下一个 } } public static void main(String agrs[]){ Main test = new Main(); test.operation(); }
}
|
设计模式之迭代器模式,iterator
最新推荐文章于 2021-12-02 21:45:38 发布