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使用渠道:点击直达
相关推荐
文丑颜不良啊16 小时前
LeetCode2981~3000题目解析
java·leetcode
nice_lcj52017 小时前
【从零理解 Spring AI · 13】RAG 要解决什么:把“闭卷考试“变成“开卷“
java·spring·检索增强·rag·spring ai·ai应用开发
学长毕设18 小时前
基于SpringBoot军事纪念馆管理系统设计与实现-附源码
java·spring boot·后端
这个昵称不容易19 小时前
SpringBoot 医疗病历交互系统的设计与实现:192 个 Java 文件、256 个接口、22 张表,附真实运行截图
java·springboot·毕设
驭渊的小故事20 小时前
订单服务如何调用商品服务?一次 RestTemplate 跨服务调用入门
java·开发语言·php
文丑颜不良啊1 天前
LeetCode3001~3020题目解析
java·leetcode
山楂树の1 天前
Java 字符串高效处理:StringBuilder、StringBuffer、StringJoiner
java·开发语言
wy_hhxx1 天前
《Agent设计模式 图解可复用智能体架构》上篇内容整理
设计模式·架构·ai agent
AAA修煤气灶刘哥1 天前
DSH Super-agent 双层架构:如何兼顾后台执行与持续响应
人工智能·后端·设计模式
.痞老板.1 天前
java ee--文件操作和IO
java·java-ee