十七、迭代器模式

  • 目的 : 提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露其内部的表示。
  • 核心 : 定义迭代器接口(hasNext(), next())。聚合对象(如集合)提供创建相应迭代器的方法。迭代器封装了遍历集合的细节。
  • 场景 :适用于遍历复杂数据结构,如多维数组、树或图,简化代码,提高可读性。

首先是迭代器接口,定义了迭代器的基本操作,支持双向遍历。

java 复制代码
package iterator;

public interface IIterator<T> {	

    boolean hasNext();      // 是否有下一个元素
    boolean hasPrevious();  // 是否有前一个元素

    T next();               // 获取下一个元素
    T previous();           // 获取前一个元素
}

具体迭代器实现接口

java 复制代码
package iterator;

public class MyIterator<T> implements IIterator<T> {

	private ICollection<T> collection;			// 持有对集合的引用
	private int index = 0;						// 当前迭代位置

	public MyIterator(ICollection<T> collection) {
		this.collection = collection;
	}

	@Override
	public boolean hasNext() {					// 检查是否有下一个
		return index < this.collection.size();
	}

	@Override
	public boolean hasPrevious() {				// 检查是否有上一个
		return index > 0;
	}

	@Override
	public T next() {							// 获取下一个
		return this.collection.get(index++);
	}

	@Override
	public T previous() {						// 获取上一个
		return this.collection.get(index--);
	}
}

接口 定义了集合的基本操作 和 获取迭代器的方法

java 复制代码
package iterator;

public interface ICollection<T> {	

    IIterator<T> iterator();  // 创建迭代器

    void add(T t);           // 添加元素

    T get(int index);        // 获取元素

    int size();              // 获取大小
}
java 复制代码
package iterator;

import java.util.Arrays;

public class MyCollection<T> implements ICollection<T> {

	private T[] arys;						 // 内部数组存储元素
	private int index = -1;					// 当前索引  跟踪当前元素数量
	private int capacity = 6;			   // 初始容量  数组满时自动扩容(每次增加6)

	@SuppressWarnings("unchecked") // 抑制 编译器关于 强制类型转换 的警告
	public MyCollection() {
		this.arys = (T[])new Object[capacity];	// 先创建 Object[] 再强制转型为 T[]
	}										   // 创建一个泛型数组 arys,初始大小为 capacity(默认为6)

	@Override
	public IIterator<T> iterator() {	// 创建一个迭代器
		return new MyIterator<>(this);  /*    返回一个新的 MyIterator 实例	  */
	}									// 将当前集合对象(this)传递给迭代器,使迭代器能访问集合的元素

	@Override
	public void add(T t) {
		index++;										    // 跟踪当前元素数量
		if(index == capacity){								// 数组满时
			capacity += 6;									// 自动扩容(每次增加6)
			this.arys = Arrays.copyOf(arys, capacity);
		}
		this.arys[index] = t;
	}

	@Override
	public T get(int index) {
		if(index < size()){					// 检查索引是否有效
			return this.arys[index];
		}
		return null;						// 无效索引返回null
	}

	@Override
	public int size() {						// 返回集合中当前元素的数量
		return index + 1;
	}
}

函数入口

java 复制代码
package iterator;

public class MainTest {
	public static void main(String[] args) {
		ICollection<Object> collection = new MyCollection<>();
		add(collection, "a", "b", "c", "d", 3, 5, 6, 7);
		for(IIterator<Object> iterator = collection.iterator(); iterator.hasNext();){
			System.out.println(iterator.next());
		}
	}

	@SuppressWarnings("unchecked")
	static<T> void add(ICollection<T> c,T ...a){
		for(T t : a){
			c.add(t);
		}
	}

最终会依次输出:

复制代码
a
b
c
d
3
5
6
7
相关推荐
我爱cope2 小时前
【从0开始学设计模式-8| 桥接模式】
java·设计模式·桥接模式
Lsk_Smion2 小时前
Hot100(开刷) 之 环形链表(II)-- 随机链表的复制 -- 翻转二叉树
java·后端·kotlin·力扣·hot100
indexsunny2 小时前
互联网大厂Java求职面试实战:Spring Boot与微服务架构解析
java·spring boot·redis·kafka·spring security·flyway·microservices
lulu12165440782 小时前
Claude Code Routines功能深度解析:24小时云端自动化开发指南
java·人工智能·python·ai编程
ch.ju2 小时前
Java程序设计(第3版)第二章——关系运算符
java
Tirzano2 小时前
springsession全能序列化方案
java·开发语言
我登哥MVP2 小时前
【SpringMVC笔记】 - 2 - @RequestMapping
java·spring boot·spring·servlet·tomcat·intellij-idea·springmvc
殷紫川2 小时前
深度剖析:Java 并发三大量难题 —— 死锁、活锁、饥饿全解
java
云烟成雨TD2 小时前
Spring AI Alibaba 1.x 系列【14】ReactAgent 工具执行异常处理
java·人工智能·spring