Java设计模式-迭代器模式、迭代器模式是什么、怎么使用

继续整理记录这段时间来的收获,详细代码可在我的Gitee仓库Java设计模式克隆下载学习使用!

6.9 迭代器者模式

6.9.1 定义

提供一个对象来顺序访问聚合对象中的一系列数据,而不暴露聚合对象的内部表示

6.9.2 结构

  • 抽象聚合(Aggregate)角色:定义存储、添加、删除聚合元素以及创建迭代器对象接口
  • 具体聚合角色(Concrete Aggregate):实现抽象聚合类,返回具体迭代器实例
  • 抽象迭代器角色(Iterator):定义访问和遍历聚合元素的接口,通常包括hasNext()、next()方法
  • 具体迭代器角色(Concrete Iterator):实现抽象迭代器接口中所定义的方法,完成对聚合对象的遍历,记录遍历的当前位置

6.9.3 案例(学生存储)

  • 学生类
public class Student {  
    String name;  
    String number;  
    public Student(String name, String number) {  
        this.name = name;  
        this.number = number;  
    }  
    @Override  
    public String toString() {  
        return "Student{" +  
                "name='" + name + '\'' +  
                ", number='" + number + '\'' +  
                '}';  
    }  
}
  • 抽象迭代器
public interface IteratorStudent {  
    public boolean hasNext();  
    public Student next();  
}
  • 具体迭代器
public class IteratorStudentImpl implements IteratorStudent{  
    private List<Student> list;  
    private int position = 0;  
    public IteratorStudentImpl(List<Student> list) {  
        this.list = list;  
    }  
    @Override  
    public boolean hasNext() {  
        return position < list.size();  
    }  
    @Override  
    public Student next() {  
        return list.get(position ++);  
    }  
}
  • 抽象聚合
public interface StudentAggregate {  
//    添加学生  
    public void addStudent(Student student);  
//    删除学生  
    public void removeStudent(Student student);  
//    迭代器对象  
    IteratorStudent getStudentIterator();  
}
  • 具体聚合类
public class StudentAggregateImpl implements StudentAggregate{  
    private List<Student> list = new ArrayList<>();  
    @Override  
    public void addStudent(Student student) {  
        list.add(student);  
    }  
    @Override  
    public void removeStudent(Student student) {  
        list.remove(student);  
    }  
    @Override  
    public IteratorStudent getStudentIterator() {  
        return new IteratorStudentImpl(list);  
    }  
}
  • 测试
    public static void main(String[] args) {  
//        创建学生  
        Student student1 = new Student("张三","1211");  
        Student student2 = new Student("李四","1212");  
        Student student3 = new Student("王五","1213");  
//        创建聚合对象  
        StudentAggregate studentAggregate = new StudentAggregateImpl();  
//        添加学生对象  
        studentAggregate.addStudent(student1);  
        studentAggregate.addStudent(student2);  
        studentAggregate.addStudent(student3);  
//        获取迭代器遍历  
        IteratorStudent studentIterator = studentAggregate.getStudentIterator();  
        while (studentIterator.hasNext()){  
            System.out.println(studentIterator.next());  
        }  
    }
  • 结果
    ![[Pasted image 20230116165303.png]]
  • 类图![[Pasted image 20230116165331.png]]

6.9.4 优缺点

6.9.4.1 优点
  • 支持以不同方式遍历聚合对象,定义多种遍历模式:只需要定义不同迭代器就可改变原有遍历模式
  • 简化聚合类:在原有的聚合对象中不需要再自行提供数据遍历等方法
  • 扩展方便:由于引入抽象层,增加新聚合类和迭代器方便,无需修改原有代码
6.9.4.2 缺点

增加类个数,一定程度上增加系统复杂性

6.9.5 使用场景

  • 为聚合对象提供多种遍历方法
  • 为遍历不同的聚合结构提供一个统一的接口
  • 访问聚合对象的内容而无需暴露其内部细节

6.9.6 JDK源码

迭代器模式在JAVA中的很多集合中被应用,简单如下:

List<String> list = new ArrayList<>();
Iterator<String> iterator = list.iterator();//Iterator接口子实现类对象
while(iterator.hasNext()){
System.out.println(iterator.next());
}

以ArrayList为例说明:

  • List:抽象聚合类
  • ArrayList:具体聚合类
  • Iterator:抽象迭代器
  • list.iterator:具体迭代器对象,返回实现了Iterator接口方法
    ArrayList具体代码实现:
public class ArrayList<E> extends AbstractList<E>  
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
                public Iterator<E> iterator() {  
			    return new 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;
	public boolean hasNext() {  
    return cursor != size;  
	}  
	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];  
}
 }}

意思就是在iterator方法中返回了一个实例化的Iterator对象,其中Itr是内部类,实现Iterator接口并重写了其中的抽象方法
使用建议:
自己定义容器类实现java.utl.Iterator<>并实现其中的iterator()方法使其返回一个java.utl.Iterator实现类即可

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值