设计模式 - 迭代器模式

本文摘自书籍《设计模式》
此系列文章GitHub地址

行为型 - 迭代器模式(Iterator Pattern)

定义

提供一种方法来访问聚合对象,而不用暴露这个对象的内部表示,其别名为游标。迭代器是一种行为型模式。

模式结构

public interface Iterator {
    void first();
    void last();
    boolean isFirst();
    boolean isLast();
}

public class InteratorA implements Iterator {
    private Object[] objs;
    //实现
}

Java中集合类型都有实现,这里就不再对此模式进行赘述,大体就是,对集合中元素的遍历操作,贴上java.util.Iterator接口的定义:

package java.util;

import java.util.function.Consumer;

public interface Iterator<E> {

    boolean hasNext();

    E next();

    default void remove() {
        throw new UnsupportedOperationException("remove");
    }

    /**
     * 剩余元素遍历执行action.accept()方法 
     */
    default void forEachRemaining(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        while (hasNext())
            action.accept(next());
    }
}

java中集合接口与此相关的方法定义:

Iterator<E> iterator();

集合一般会在内部实现Iterator接口,作为实现上面方法的返回具体迭代器,下面是AbstractList中的实现:

private class Itr implements Iterator<E> {
    /**
    * Index of element to be returned by subsequent call to next.
    */
    int cursor = 0;

    /**
    * Index of element returned by most recent call to next or
    * previous.  Reset to -1 if this element is deleted by a call
    * to remove.
    */
    int lastRet = -1;

    /**
    * The modCount value that the iterator believes that the backing
    * List should have.  If this expectation is violated, the iterator
    * has detected concurrent modification.
    */
    int expectedModCount = modCount;

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

    public E next() {
        checkForComodification();
        try {
            int i = cursor;
            E next = get(i);
            lastRet = i;
            cursor = i + 1;
            return next;
        } catch (IndexOutOfBoundsException e) {
            checkForComodification();
            throw new NoSuchElementException();
        }
    }

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

        try {
            AbstractList.this.remove(lastRet);
            if (lastRet < cursor)
                cursor--;
            lastRet = -1;
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException e) {
            throw new ConcurrentModificationException();
        }
    }

    final void checkForComodification() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值