设计模式——迭代器模式

157 阅读1分钟

1. 迭代器模式概述

迭代器模式用于顺序访问集合对象的元素,不需要知道集合对象的底层表示。

(1) 适用情况

需要对聚合对象进行迭代时,可以考虑使用迭代器模式。

(2) 优点

使用迭代器,可以实现多个迭代接口,从而以不同的方式进行遍历。

(3) 缺点

为了适配不同的聚合对象,可能需要实现不同的迭代器,从而导致类的成倍增加。

2. 迭代器模式实例

这里我们写一个简单的迭代器模式,来从聚合对象中获取颜色。

(1) 声明迭代器接口

public interface Iterator {
    boolean hasNext();

    Object next();
}

(2) 创建聚合对象类和实现迭代器接口的内部迭代器类

public class ColorRepository {
    private String[] colors = {"Red", "Yellow", "Blue"};

    public Iterator getIterator() {
        return new ColorIterator();
    }

    private class ColorIterator implements Iterator {
        private int index = 0;

        @Override
        public boolean hasNext() {
            return index < colors.length;
        }

        @Override
        public Object next() {
            if (hasNext()) {
                return colors[index++];
            }
            return null;
        }
    }
}

(3) 迭代打印所有颜色

public class IteratorDemo {
    public static void main(String[] args) {
        ColorRepository colorRepository = new ColorRepository();

        Iterator iterator = colorRepository.getIterator();

        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

运行结果:
image.png

3. 一些思考

在java.util包中,就有Iterator的接口,ArrayList之所以可以使用迭代器进行迭代,是因为在他内部的Itr类就实现了Iterator接口,并提供了对应的方法实现。

参考引用

迭代器模式:www.runoob.com/design-patt…