迭代器设计模式

如果遇到要对某个类内部数据逐行计算的场景,可以采用迭代器设计模式自定义一个迭代器

public class Caculator implements Iterable {

    List<Object> result;

    @Override
    public Iterator iterator() {
        return new Itr();
    }

    private class Itr implements Iterator<Object> {
        int cursor = 0;

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

        @Override
        public Object next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            return caculate();
        }

        private Object caculate() {
            Object row = result.get(cursor);
            // 计算
            cursor++;
            return new Object();
        }
    }
    
    public static void main(String[] args) {
        Caculator caculator = new Caculator();
        Iterator<Object> iterator = caculator.iterator();
        while (iterator.hasNext()) {
            Object r = iterator.next();
            // 处理该行数据
        }
    }
}


你可能感兴趣的:(java)