GOF——迭代器模式

JDK内置迭代器类似.主要用于遍历对象


interface MyIterator {
    boolean isFirst();

    boolean isLast();

    void first();

    Object next();

    boolean hasNext();
}

class ConcreteMyAggregate {
    private List<String> list = new ArrayList<>();

    public void add(String str) {
        this.list.add(str);
    }

    public void remove(String str) {
        this.list.remove(str);
    }

    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

    public ConcreteIterator createIterator() {
        return new ConcreteIterator();
    }

    private class ConcreteIterator implements MyIterator {
        private int cursor;

        @Override
        public boolean isFirst() {
            return cursor == 0;
        }

        @Override
        public boolean isLast() {
            return cursor == (list.size() - 1);
        }

        @Override
        public void first() {
            cursor = 0;
        }

        @Override
        public Object next() {
            String s = list.get(cursor);
            cursor++;
            return s;
        }

        @Override
        public boolean hasNext() {
            return cursor < (list.size());
        }
    }

}
/**
 * 迭代器模式
 */
public class Iterator {
    public static void main(String[] args) {
        ConcreteMyAggregate aggregate = new ConcreteMyAggregate();
        aggregate.add("1");
        aggregate.add("2");
        aggregate.add("3");
        aggregate.add("4");

        MyIterator iterator = aggregate.createIterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.isFirst() + "-->" + iterator.isLast());
            System.out.println(iterator.next());
        }

        Map<String, String> map = new HashMap<>();

        map.put("1", "456");
        map.put("2", "456");
        map.put("3", "456");
        Set<Map.Entry<String, String>> entries = map.entrySet();
        java.util.Iterator<Map.Entry<String, String>> iterator1 = entries.iterator();
        while (iterator1.hasNext()) {
            Map.Entry<String, String> next = iterator1.next();
            System.out.println(next.getKey() + "-->" + next.getValue());
        }

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值