设计模式之迭代器模式

迭代器模式(Iterator)

定义

提供一种顺序访问一个聚合对象(容器)中各个元素的方法,而又不暴露其内部的表示

使用场景

主要角色

  1. 迭代器Iterator
  2. 具体的迭代器ConcreteIterator
  3. 聚合Aggregate
  4. 具体的聚合ConcreteAggregate

类图

ArrayList真实的继承体系

示例代码

java 复制代码
public interface Iterator<E> {
    
    boolean hasNext();
    
    E next();
    
    default void remove() {
        throw new UnsupportedOperationException("remove");
    }

    default void forEachRemaining(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        while (hasNext())
            action.accept(next());
    }
}

java.util.ArrayList.Itr

java 复制代码
private class Itr implements Iterator<E> {
    int cursor;       // index of next element to return
    int lastRet = -1; // index of last element returned; -1 if no such
    int expectedModCount = modCount;

    Itr() {}

    public boolean hasNext() {
        return cursor != size;
    }

    @SuppressWarnings("unchecked")
    public E next() {
        checkForComodification();
        int i = cursor;
        if (i >= size)
            throw new NoSuchElementException();
        Object[] elementData = ArrayList.this.elementData;
        if (i >= elementData.length)
            throw new ConcurrentModificationException();
        cursor = i + 1;
        return (E) elementData[lastRet = i];
    }

    public void remove() {
        if (lastRet < 0)
            throw new IllegalStateException();
        checkForComodification();

        try {
            ArrayList.this.remove(lastRet);
            cursor = lastRet;
            lastRet = -1;
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public void forEachRemaining(Consumer<? super E> consumer) {
        Objects.requireNonNull(consumer);
        final int size = ArrayList.this.size;
        int i = cursor;
        if (i >= size) {
            return;
        }
        final Object[] elementData = ArrayList.this.elementData;
        if (i >= elementData.length) {
            throw new ConcurrentModificationException();
        }
        while (i != size && modCount == expectedModCount) {
            consumer.accept((E) elementData[i++]);
        }
        // update once at end of iteration to reduce heap write traffic
        cursor = i;
        lastRet = i - 1;
        checkForComodification();
    }

    final void checkForComodification() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
}

java.util.ArrayList#iterator

java 复制代码
public Iterator<E> iterator() {
    return new Itr();
}

工作中遇到场景

相关推荐
Michael_lcf8 小时前
Agent设计模式:思考-行动-观察循环的本质与局限
设计模式·agent设计模式·agent设计模式的本质
丰锋ff9 小时前
设计模式学习笔记
笔记·学习·设计模式
米啦啦.10 小时前
设计模式/
观察者模式·单例模式·设计模式·工厂模式
QuZhengRong12 小时前
【AI】Agent 全栈进阶|Agent 设计模式
人工智能·学习·设计模式·llm·agent
码匠许师傅13 小时前
【设计模式精讲】2. 设计原则基石:SOLID 与几条关键原则
java·设计模式·log4j
AI人工智能+电脑小能手14 小时前
大白话说Java设计模式-41-备忘录模式(源码剖析篇)
java·设计模式·备忘录模式·源码分析·serializable·undo log·spring statemachine
yinchnag15 小时前
CRTP:奇异递归模板模式在 Go 模块系统中的实现
设计模式·go
AI人工智能+电脑小能手16 小时前
大白话说Java设计模式-40-备忘录模式(业务实战篇)
java·设计模式·事务回滚·备忘录模式·状态保存·spring transactional·购物车快照
bryant_meng1 天前
【Codex】Part 19 — Codex Prompt Design Patterns
设计模式·prompt·playbook·结果优先·用证据定义完成
AI人工智能+电脑小能手1 天前
大白话说Java设计模式-38-迭代器模式(业务实战篇)
java·设计模式·迭代器模式·stream·遍历封装·集合通用·分页遍历