设计模式之迭代器模式

文章目录

定义

迭代器模式(Iterator Pattern)是行为设计模式之一,它提供了一种访问集合对象元素的方式,而不需要暴露集合的内部表示。迭代器模式可以让你顺序地访问集合中的每个元素,而无需知道集合的底层实现。这种方式支持对不同类型的集合进行统一的操作,增加了程序的灵活性和可扩展性。

主要角色:

  • Iterable(Iterable Interface): 定义了创建迭代器对象的接口。
  • Iterator(Iterator Interface): 定义了遍历集合元素所需的方法,如hasNext()和next()。
  • Concrete Iterable(Concrete Collection): 实现Iterable接口,负责创建对应的具体迭代器对象。
  • Concrete Iterator: 实现Iterator接口,完成集合元素的遍历。

示例代码

在Java中,迭代器模式已经内建于语言本身,通过Iterable和Iterator接口实现。下面是一个简化的例子,展示如何自定义一个集合类并实现迭代器模式。

java 复制代码
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

// 具体的可迭代集合类
class CustomCollection implements Iterable<String> {
    private List<String> items = new ArrayList<>();

    public CustomCollection(String... elements) {
        for (String element : elements) {
            items.add(element);
        }
    }

    @Override
    public Iterator<String> iterator() {
        return new CustomIterator();
    }

    // 内部类,实现迭代器
    private class CustomIterator implements Iterator<String> {
        private int index = 0;

        @Override
        public boolean hasNext() {
            return index < items.size();
        }

        @Override
        public String next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            return items.get(index++);
        }
    }
}

// 客户端代码
public class IteratorPatternDemo {
    public static void main(String[] args) {
        CustomCollection collection = new CustomCollection("A", "B", "C", "D");

        // 使用迭代器遍历集合
        for (String item : collection) {
            System.out.println(item);
        }
    }
}
相关推荐
yunhuibin26 分钟前
DP学习——简单工厂模式
设计模式·简单工厂模式
java小郭28 分钟前
设计模式之责任链模式
设计模式·责任链模式
CodeLinghu2 小时前
【设计模式】策略模式(定义 | 特点 | Demo入门讲解)
设计模式·bash·策略模式
繁星十年5 小时前
《C++20设计模式》命令模式思考
设计模式·命令模式·c++20
明戈戈14 小时前
设计模式-模板方法模式
设计模式·模板方法模式
python资深爱好者14 小时前
在什么情况下你会使用设计模式
设计模式
PingCAP18 小时前
Dify + TiDB Vector,快速构建你的AI Agent
数据库·人工智能·设计模式
BoldExplorer19 小时前
设计模式(四)责任链模式
设计模式·责任链模式
GIS_JH19 小时前
设计模式简单示例
设计模式
搬砖的小熊猫20 小时前
设计模式探索:策略模式
设计模式·策略模式