设计模式之迭代器模式

什么是迭代器模式

    迭代器模式是提供一种方法来访问聚合对象,而不用暴露这个对象的内部结构。
    迭代器模式主要包含以下几个角色:
        Iterator(抽象迭代器):定义了访问和遍历元素的接口,声明了用于遍历数据元素的方法。
        ConcreteIterator(具体迭代器):实现了抽象迭代器接口,完成对聚合对象的遍历,同时在具体迭代器中通过下标来记录在聚合对象中所处的当前位置。
        Aggregate(抽象聚合类):用于存储和管理元素对象。
        ConcreteAggregate(具体聚合类):实现了抽象聚合类中的方法。

迭代器模式的优缺点

优点
  1. 支持以不同的方式遍历一个聚合对象,在一个聚合对象中可以定义多种遍历方式。
  2. 迭代器简化了聚合类。
  3. 增加新的聚合类和迭代器类方便,符合开闭原则。
缺点
  1. 将存储数据和遍历数据分离,增加新的聚合类需要对应增加迭代器类,类的个数成对增加,在一定程度上增加了系统的复杂性。
  2. 抽象迭代器的设计难度较大,需要充分考虑系统将来的发展。

迭代器模式的应用场景

  1. 访问一个聚合对象的内容而无需暴露内部表示。
  2. 需要为一个聚合对象提供多种遍历方式。
  3. 为遍历不同的聚合结构提供一个统一的接口,在该接口的实现类中为不同的聚合结构提供不同的遍历方式。

迭代器模式的案例

// 抽象聚合类
public interface College {
    String getName();

    /**
     * 增加系的方法
     *
     * @param name name
     * @param desc desc
     */
    void addDepartment(String name, String desc);

    /**
     * 返回一个迭代器,遍历
     *
     * @return Iterator
     */
    Iterator createIterator();
}


@Data
public class Department {

    private String name;
    private String desc;

    public Department(String name, String desc) {
        super();
        this.name = name;
        this.desc = desc;
    }

}

// 具体聚合类
public class ComputerCollege implements College {

    Department[] departments;

    /**
     * 保存当前数组的对象个数
     */
    int numOfDepartment = 0;


    public ComputerCollege() {
        departments = new Department[5];
        addDepartment("Java专业", " Java专业 ");
        addDepartment("PHP专业", " PHP专业 ");
        addDepartment("大数据专业", " 大数据专业 ");
    }

    @Override
    public String getName() {
        return "计算机学院";
    }

    @Override
    public void addDepartment(String name, String desc) {
        Department department = new Department(name, desc);
        departments[numOfDepartment] = department;
        numOfDepartment += 1;
    }

    @Override
    public Iterator createIterator() {
        return new ComputerCollegeIterator(departments);
    }

}

// 具体迭代器类
public class ComputerCollegeIterator implements Iterator {

    Department[] departments;

    int position = 0;


    public ComputerCollegeIterator(Department[] departments) {
        this.departments = departments;
    }

    @Override
    public boolean hasNext() {
        return position < departments.length && departments[position] != null;
    }

    @Override
    public Object next() {
        Department department = departments[position];
        position += 1;
        return department;
    }

    @Override
    public void remove() {

    }

}

public class OutPutImpl {

    List<College> collegeList;

    public OutPutImpl(List<College> collegeList) {

        this.collegeList = collegeList;
    }

    public void printCollege() {
        //从collegeList 取出所有学院, Java 中的 List 已经实现Iterator

        for (College college : collegeList) {
            //取出一个学院
            System.out.println("=== " + college.getName() + "=====");
            printDepartment(college.createIterator());
        }
    }

    public void printDepartment(Iterator iterator) {
        while (iterator.hasNext()) {
            Department d = (Department) iterator.next();
            System.out.println(d.getName());
        }
    }

}

public static void main(String[] args) {
    List<College> collegeList = new ArrayList<>();

    ComputerCollege computerCollege = new ComputerCollege();
    collegeList.add(computerCollege);

    OutPutImpl outPutImpl = new OutPutImpl(collegeList);
    outPutImpl.printCollege();
}

![在这里插入图片描述](https://img-blog.csdnimg.cn/0183ff5c66b647e7864fb38621a9fb74.png#pic_center)

迭代器模式在源码中的应用

ArrayList
public interface List<E> extends Collection<E> {

    Iterator<E> iterator();
    boolean add(E e);
    boolean remove(Object o);

}

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{

    ......
    
    public Iterator<E> iterator() {
        return new Itr();
    }

    /**
     * An optimized version of AbstractList.Itr
     */
    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();
        }
    }

    
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值