23种设计模式之迭代器模式(Iterator Pattern)

693 阅读3分钟

迭代器模式概念

迭代器模式是一种对象行为型设计模式。它提供了遍历集合对象所需的标准接口,而不暴露集合对象的实现方式

在Java编程中,常见的集合类包括List、Set和Map等,这些都内部维护着一个元素列表。通过迭代器模式,对于任何一种集合对象,在不了解其内部实现的情况下,都可以轻松地遍历其中的每个元素,从而简化了代码的编写和维护。

迭代器模式构成部分

迭代器模式由两个主要组成部分构成:迭代器(Iterator)和可迭代对象(Iterable)。迭代器用于定义访问和遍历元素的接口,而可迭代对象用于返回迭代器。

下面是迭代器模式的基本结构:

迭代器(Iterator):定义访问和遍历聚合对象元素的接口; 具体迭代器(ConcreteIterator):实现迭代器接口,并对聚合对象进行遍历和存储当前遍历位置等操作; 可迭代对象(Iterable):定义获取迭代器的接口; 具体可迭代对象(ConcreteIterable):实现可迭代对象接口,返回具体的迭代器实例。 迭代器模式的使用步骤如下:

定义聚合对象的对象结构,包含 add()、remove()和 get()等方法; 定义迭代器接口 Iterator,并声明 getFirst()、getNext()、isDone() 和 getCurrentItem() 方法; 实现具体迭代器 ConcreteIterator 类,维护一个指向当前位置的指针,实现 Iterator 接口中的方法实现元素遍历; 实现可迭代对象 Iterable 接口,并实现创建迭代器实例的方法 iterator(); 在客户端代码中使用该聚合对象和迭代器通过 hasNext()、next() 等方法对集合对象进行访问和遍历。 总之,迭代器模式是一种非常有用且广泛应用于实际开发的设计模式,它可以有效地解耦集合对象和其遍历方式,使得代码更加简洁和易于维护。

迭代器模式案例

假设我们有一个存储了学生信息的集合类 StudentList,包含了 addStudent()、removeStudent()和 getStudent()等方法。现在,我们需要基于迭代器模式来遍历这个学生信息集合。具体步骤如下:

定义迭代器接口 Iterator:

public interface Iterator {
    public boolean hasNext();
    public Object next();
}

实现具体的迭代器类 ConcreteIterator:

public class ConcreteIterator implements Iterator {
    private StudentList studentList;
    private int index = 0;

    public ConcreteIterator(StudentList list) {
        this.studentList = list;
    }

    @Override
    public boolean hasNext() {
        return index < studentList.getLength();
    }

    @Override
    public Object next() {
        if (hasNext()) {
            return studentList.getStudent(index++);
        }
        return null;
    }
}

定义可迭代对象接口 Iterable:

public interface Iterable {
    public Iterator iterator();
}

实现具体的可迭代对象类 ConcreteIterable:

public class ConcreteIterable implements Iterable {
    private StudentList studentList;

    public ConcreteIterable(StudentList list) {
        this.studentList = list;
    }

    @Override
    public Iterator iterator() {
        return new ConcreteIterator(studentList);
    }
}

在客户端代码中使用聚合对象和迭代器进行遍历:

public static void main(String[] args) {
    StudentList list = new StudentList();
    list.addStudent("Tom");
    list.addStudent("Mary");
    list.addStudent("John");

    ConcreteIterable iterable = new ConcreteIterable(list);
    Iterator iterator = iterable.iterator();
    while (iterator.hasNext()) {
        String name = (String) iterator.next();
        System.out.println(name);
    }
}

上面的代码中,我们首先定义了迭代器接口 Iterator,并在迭代器具体实现类 ConcreteIterator 中实现了遍历集合对象的逻辑。然后,我们定义了可迭代对象接口 Iterable,并在其实现类 ConcreteIterable 中返回具体的迭代器实例。最后,在客户端代码中使用该聚合对象和迭代器通过 hasNext()、next() 等方法对集合对象进行访问和遍历。

迭代器模式小结

总的来说,迭代器模式将聚合对象和遍历方式分离,提供了一种通用的遍历机制,使得不同类型的集合对象均可以方便地进行遍历,并且通过迭代器接口也可以更加灵活地定义迭代器的行为

好了,本篇文章就先分享到这里了,后续将会继续介绍23种设计模式之其他模式,感谢大佬认真读完支持咯~