小菜成长记(十一)——迭代器模式

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);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值