设计模式-23种设计模式-行为型-迭代器模式
一、迭代器模式介绍
二、迭代器模式引入
需求:
UML类图:
代码实现(Java):
import java.util.function.Consumer; /** * An iterator over a collection. {@code Iterator} takes the place of * {@link Enumeration} in the Java Collections Framework. Iterators * differ from enumerations in two ways: * * <ul> * <li> Iterators allow the caller to remove elements from the * underlying collection during the iteration with well-defined * semantics. * <li> Method names have been improved. * </ul> * * <p>This interface is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * * @param <E> the type of elements returned by this iterator * * @author Josh Bloch * @see Collection * @see ListIterator * @see Iterable * @since 1.2 */ public interface Iterator<E> { /** * Returns {@code true} if the iteration has more elements. * (In other words, returns {@code true} if {@link #next} would * return an element rather than throwing an exception.) * * @return {@code true} if the iteration has more elements */ boolean hasNext(); /** * Returns the next element in the iteration. * * @return the next element in the iteration * @throws NoSuchElementException if the iteration has no more elements */ E next(); /** * Removes from the underlying collection the last element returned * by this iterator (optional operation). This method can be called * only once per call to {@link #next}. The behavior of an iterator * is unspecified if the underlying collection is modified while the * iteration is in progress in any way other than by calling this * method. * * @implSpec * The default implementation throws an instance of * {@link UnsupportedOperationException} and performs no other action. * * @throws UnsupportedOperationException if the {@code remove} * operation is not supported by this iterator * * @throws IllegalStateException if the {@code next} method has not * yet been called, or the {@code remove} method has already * been called after the last call to the {@code next} * method */ default void remove() { throw new UnsupportedOperationException("remove"); } /** * Performs the given action for each remaining element until all elements * have been processed or the action throws an exception. Actions are * performed in the order of iteration, if that order is specified. * Exceptions thrown by the action are relayed to the caller. * * @implSpec * <p>The default implementation behaves as if: * <pre>{@code * while (hasNext()) * action.accept(next()); * }</pre> * * @param action The action to be performed for each element * @throws NullPointerException if the specified action is null * @since 1.8 */ default void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); while (hasNext()) action.accept(next()); } }
import java.util.Iterator; public class ComputerCollegeIterator implements Iterator { //这里我们需要Department 是以怎样的方式存放=>数组 Department[] departments; int position = 0; //遍历的位置 public ComputerCollegeIterator(Department[] departments) { this.departments = departments; } //判断是否还有下一个元素 @Override public boolean hasNext() { if(position >= departments.length || departments[position] == null) { return false; }else { return true; } } @Override public Object next() { Department department = departments[position]; position += 1; return department; } //删除的方法,默认空实现 public void remove() { } }
import java.util.Iterator; import java.util.List; public class InfoColleageIterator implements Iterator { List<Department> departmentList; // 信息工程学院是以List方式存放系 int index = -1;//索引 public InfoColleageIterator(List<Department> departmentList) { this.departmentList = departmentList; } //判断list中还有没有下一个元素 @Override public boolean hasNext() { if(index >= departmentList.size() - 1) { return false; } else { index += 1; return true; } } @Override public Object next() { return departmentList.get(index); } //空实现remove public void remove() { } }
import java.util.Iterator; public interface College { public String getName(); //增加系的方法 public void addDepartment(String name, String desc); //返回一个迭代器,遍历 public Iterator createIterator(); }
import java.util.Iterator; public class ComputerCollege implements College { Department[] departments; int numOfDepartment = 0 ;// 保存当前数组的对象个数 public ComputerCollege() { departments = new Department[5]; addDepartment("Java专业", " Java专业 "); addDepartment("PHP专业", " PHP专业 "); addDepartment("大数据专业", " 大数据专业 "); } @Override public String getName() { return "计算机学院"; } @Override public void addDepartment(String name, String desc) { Department department = new Department(name, desc); departments[numOfDepartment] = department; numOfDepartment += 1; } @Override public Iterator createIterator() { return new ComputerCollegeIterator(departments); } }
import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class InfoCollege implements College { List<Department> departmentList; public InfoCollege() { departmentList = new ArrayList<Department>(); addDepartment("信息安全专业", " 信息安全专业 "); addDepartment("网络安全专业", " 网络安全专业 "); addDepartment("服务器安全专业", " 服务器安全专业 "); } @Override public String getName() { return "信息工程学院"; } @Override public void addDepartment(String name, String desc) { Department department = new Department(name, desc); departmentList.add(department); } @Override public Iterator createIterator() { return new InfoColleageIterator(departmentList); } }
public class Department { private String name; private String desc; public Department(String name, String desc) { super(); this.name = name; this.desc = desc; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } }
import java.util.Iterator; import java.util.List; public class OutPutImpl { //学院集合 List<College> collegeList; public OutPutImpl(List<College> collegeList) { this.collegeList = collegeList; } //遍历所有学院,然后调用printDepartment 输出各个学院的系 public void printCollege() { //从collegeList 取出所有学院, Java 中的 List 已经实现Iterator Iterator<College> iterator = collegeList.iterator(); while(iterator.hasNext()) { //取出一个学院 College college = iterator.next(); System.out.println("=== "+college.getName() +"=====" ); printDepartment(college.createIterator()); //得到对应迭代器 } } //输出 学院输出 系 public void printDepartment(Iterator iterator) { while(iterator.hasNext()) { Department d = (Department)iterator.next(); System.out.println(d.getName()); } } }
import java.util.ArrayList; import java.util.List; public class Client { public static void main(String[] args) { //创建学院 List<College> collegeList = new ArrayList<College>(); ComputerCollege computerCollege = new ComputerCollege(); InfoCollege infoCollege = new InfoCollege(); collegeList.add(computerCollege); //collegeList.add(infoCollege); OutPutImpl outPutImpl = new OutPutImpl(collegeList); outPutImpl.printCollege(); } }
三、迭代器模式在JDK-ArrayList集合应用的源码分析
四、迭代器模式注意事项和细节
分类:
DesignPattern
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器