Featured image of post Java设计模式-迭代器模式Iterator

Java设计模式-迭代器模式Iterator

相关文章

【合集】Java设计模式

迭代器模式

迭代器

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
public interface StudentIterator {
    boolean hasNext();
    Student next();
}
public static class StudentIteratorImpl implements StudentIterator {
    private final List<Student> list;
    private int position = 0;
    public StudentIteratorImpl(List<Student> list) {
        this.list = list;
    }
    @Override
    public boolean hasNext() {
        return position < list.size();
    }
    @Override
    public Student next() {
        return list.get(position++);
    }
}

聚合角色

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public interface StudentAggregate {
    void addStudent(Student student);
    void removeStudent(Student student);
    StudentIterator getStudentIterator();
}
public static class StudentAggregateImpl implements StudentAggregate {
    private final List<Student> list = new ArrayList<>();
    @Override
    public void addStudent(Student student) {
        this.list.add(student);
    }
    @Override
    public void removeStudent(Student student) {
        this.list.remove(student);
    }
    @Override
    public StudentIterator getStudentIterator() {
        return new StudentIteratorImpl(list);
    }
}

实体类

1
2
3
4
5
6
7
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class Student {
    private String name;
    private String number;
}

客户端调用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
StudentAggregate aggregate = new StudentAggregateImpl();
aggregate.addStudent(new Student("张三", "001"));
        aggregate.addStudent(new Student("李四", "002"));
        aggregate.addStudent(new Student("王五", "003"));
        aggregate.addStudent(new Student("赵六", "004"));

StudentIterator iterator = aggregate.getStudentIterator();
while (iterator.hasNext()) {
Student student = iterator.next();
    System.out.println(student);
}

输出

1
2
3
4
a20_迭代器模式.Student(name=张三, number=001)
a20_迭代器模式.Student(name=李四, number=002)
a20_迭代器模式.Student(name=王五, number=003)
a20_迭代器模式.Student(name=赵六, number=004)

应用

{@link List}抽象聚合角色 {@link ArrayList}具体聚合角色 {@link java.util.Iterator}抽象迭代器 {@link ArrayList.Itr}具体迭代器

要想使用迭代器模式,只要让我们自己定义的容器类实现{@link Iterable},并实现其中的iterator()方法使其返回一个{@link java.util.Iterator}的实现类就可以了。

皖ICP备2024056275号-1
发表了78篇文章 · 总计149.56k字
本站已稳定运行