Java教程

java设计模式系列17——迭代器设计模式

本文主要是介绍java设计模式系列17——迭代器设计模式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

迭代器设计模式

提供一种方法顺序访问一个聚合对象中各个元素, 而又无须暴露该对象的内部实现,属于行为型模式

应该是java中应用最多的设计模式之一

提到迭代器,想到它是与集合相关的,集合也叫容器,可以将集合看成是一个可以包容对象的容器,例如List,Set,Map,甚至数组都可以叫做集合,迭代器的作用就是把容器中的对象一个一个地遍历出来

应用场景

  • 一般来说,迭代器模式是与集合是共存的,只要实现一个集合,就需要同时提供这个集合的迭代器,就像java中的Collection,List、Set、Map等 都有自己的迭代器
  • JAVA 中的 iterator迭代器

编码实战

自定义一个集合容器,并实现里面的迭代器功能,List集合容器的简化版本

抽象迭代器

public interface MyIterator {

    /**
     * 获取下一个元素
     * @return
     */
    Object next();

    /**
     * 是否有下一个元素
     * @return
     */
    boolean hasNext();

    /**
     * 删除元素
     * @param obj
     * @return
     */
    Object remove(Object obj);
}

实现/具体 迭代器

public class ConcreteIterator implements MyIterator{

    private List list;

    private int index = 0;

    public ConcreteIterator(List list) {
        this.list = list;
    }

    @Override
    public Object next() {
        Object obj = null;
        if (this.hasNext()){
            // 如果有则返回
            obj = this.list.get(index);
            index++;
        }
        return obj;
    }

    @Override
    public boolean hasNext() {
        if (index == list.size()){
            return false;
        }
        return true;
    }

    @Override
    public Object remove(Object obj) {
        return list.remove(obj);
    }
}

抽象容器

public interface ICollection {

    void add(Object obj);

    void remove(Object obj);

    MyIterator iterator();

}

具体容器

public class MyCollection implements ICollection{

    private List list = new ArrayList();

    @Override
    public void add(Object obj) {
        list.add(obj);
    }

    @Override
    public void remove(Object obj) {
        list.remove(obj);
    }

    @Override
    public MyIterator iterator() {
        return new ConcreteIterator(list);
    }
}

使用

public static void main(String[] args) {
    ICollection collection = new MyCollection();
    collection.add("雷军");
    collection.add("董明珠");

    MyIterator iterator = collection.iterator();
    while (iterator.hasNext()) {
        Object obj = iterator.next();
        System.out.println(obj);
    }

}

小结

优点

  • 可以做到不暴露集合的内部结构,又可让外部代码透明地访问集合内部的数据

  • 支持以不同的方式遍历一个聚合对象

缺点

  • 对于比较简单的遍历(像数组或者有序列表),使用迭代器方式遍历较为繁琐
  • 迭代器模式在遍历的同时更改迭代器所在的集合结构会导致出现异常
这篇关于java设计模式系列17——迭代器设计模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!