Java设计模式之迭代器模式

迭代器模式(Iterator Pattern)是一种行为型设计模式,它提供一种方法来顺序访问一个容器对象中的各个元素,而无需暴露该容器对象的内部表示。迭代器模式将迭代逻辑封装在一个独立的迭代器对象中,使得可以在不暴露容器内部结构的情况下,通过迭代器按序访问容器中的元素。

迭代器模式的主要参与者包括以下几个角色:

  1. 迭代器(Iterator):定义访问和遍历元素的接口,具备移动到下一个元素、获取当前元素等方法。
  2. 具体迭代器(Concrete Iterator):实现迭代器接口,负责实现具体的迭代逻辑,包括跟踪当前位置、移动到下一个元素、获取当前元素等操作。
  3. 容器(Container):定义创建迭代器的接口,可以是一个集合或聚合对象。
  4. 具体容器(Concrete Container):实现容器接口,负责创建具体迭代器对象。

下面是一个简单的示例,展示了如何使用迭代器模式来遍历一个集合对象中的元素:

java 复制代码
// 迭代器接口
interface Iterator {
    boolean hasNext();
    Object next();
}

// 具体迭代器实现
class ConcreteIterator implements Iterator {
    private String[] collection;
    private int position = 0;

    public ConcreteIterator(String[] collection) {
        this.collection = collection;
    }

    public boolean hasNext() {
        return position < collection.length;
    }

    public Object next() {
        if (hasNext()) {
            return collection[position++];
        }
        return null;
    }
}

// 容器接口
interface Container {
    Iterator createIterator();
}

// 具体容器实现
class ConcreteContainer implements Container {
    private String[] collection;

    public ConcreteContainer(String[] collection) {
        this.collection = collection;
    }

    public Iterator createIterator() {
        return new ConcreteIterator(collection);
    }
}

// 使用迭代器遍历集合
public class IteratorPatternExample {
    public static void main(String[] args) {
        String[] collection = { "Apple", "Banana", "Orange", "Grape" };
        Container container = new ConcreteContainer(collection);
        Iterator iterator = container.createIterator();

        while (iterator.hasNext()) {
            Object item = iterator.next();
            System.out.println(item);
        }
    }
}

在上面的示例中,迭代器模式被用于遍历一个包含水果名称的字符串数组。具体迭代器实现类ConcreteIterator负责实现迭代逻辑,而具体容器实现类ConcreteContainer负责创建迭代器对象。通过调用容器的createIterator()方法,可以获取一个迭代器对象,然后使用该迭代器对象遍历容器中的元素。

推荐一个ChatGPT使用渠道:点击直达
相关推荐
祎雪双十Gy7 分钟前
从 DataX 的配置加载说起:我用 FastJson2 做了一个轻量级动态配置管理库
java·后端
小锋java123413 分钟前
分享一套锋哥原创的SpringBoot4+Vue3宠物领养网站系统
java
考虑考虑3 小时前
Java实现hmacsha1加密算法
java·后端·java ee
掉鱼的猫4 小时前
Spring Boot → Solon 注解迁移实战指南:一张对照表说清楚
java·spring boot
plainGeekDev4 小时前
广播接收器 → Flow + Lifecycle
android·java·kotlin
plainGeekDev4 小时前
EventBus → SharedFlow
android·java·kotlin
带刺的坐椅4 小时前
Spring Boot → Solon 注解迁移实战指南:一张对照表说清楚
java·springboot·web·solon
青禾网络5 小时前
Web 前端如何接入 AI 音效生成:从零到可用的完整方案
人工智能·设计模式
用户3721574261355 小时前
Java 将一个 PPT 文档拆分为多个文件
java
人活一口气20 小时前
Spring Boot与AIGC的完美结合:从零搭建智能内容生成平台
java·spring boot·aigc