public class Program {
public static void main(String[] args) {
ConCreteAggregate a = new ConCreteAggregate();
a.setObjecet(0, "大鸟");
a.setObjecet(1, "小菜");
a.setObjecet(2, "行李");
a.setObjecet(3, "老外");
a.setObjecet(4, "公交内部员工");
a.setObjecet(5, "小偷");
Iterator i = new ConcreteIterator(a);
Object item = i.first();
while (!i.isDone()) {
System.out.println(i.currentItem() + "请买车票!");
i.next();
}
}
}
abstract class Iterator {
abstract Object first();
abstract Object next();
abstract boolean isDone();
abstract Object currentItem();
}
abstract class Aggregate {
abstract Iterator createIterator();
}
class ConCreteAggregate extends Aggregate {
private List<Object> items = new ArrayList<Object>();
@Override
Iterator createIterator() {
return new ConcreteIterator(this);
}
public int getCount() {
return items.size();
}
public Object getObject(int index) {
return items.get(index);
}
public void setObjecet(int index, Object object) {
items.add(index, object);
}
}
class ConcreteIterator extends Iterator {
private ConCreteAggregate aggregate;
private int current = 0;
public ConcreteIterator(ConCreteAggregate aggregate) {
this.aggregate = aggregate;
}
@Override
Object first() {
return aggregate.getObject(0);
}
@Override
Object next() {
Object ret = null;
current++;
if (current < aggregate.getCount()) {
ret = aggregate.getObject(current);
}
return ret;
}
@Override
boolean isDone() {
return current >= aggregate.getCount();
}
@Override
Object currentItem() {
return aggregate.getObject(current);
}
}
小菜成长记(十一)——迭代器模式
最新推荐文章于 2024-11-14 22:48:57 发布