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使用渠道:点击直达
相关推荐
小羊没烦恼!1 天前
微服务化的基石——持续集成
java·大数据·word·powerpoint·.net
俊昭喜喜里1 天前
java中的继承和多态的区别
java
小羊没烦恼!1 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
譕痕1 天前
JSONObject与JSONArray封装数据格式区别
java·json
胡写代码1 天前
别再前后端各写一套表单校验了
java·后端
小鱼能吃糖1 天前
缺陷修复总览 · mall电商项目:5类缺陷,1个病根,4个业务域
java·电商
此时不提桶,更待何时1 天前
01-06-A-JVM排查实战详解
java·jvm
vipxieliang1 天前
ValidX 在 DDD 领域驱动设计中的实践
java·spring boot
ba_pi1 天前
mysql 查询所有表名并授权
java
ProcessOn官方账号1 天前
java函数式编程--入门基础
java·编程·函数式编程