迭代器模式深度解析与实战案例

发布于:2025-04-10 ⋅ 阅读:(37) ⋅ 点赞:(0)

一、模式定义

迭代器模式(Iterator Pattern) 是一种行为设计模式,提供一种方法顺序访问聚合对象的元素,无需暴露其底层表示。核心思想是将遍历逻辑从聚合对象中分离,实现 遍历与存储的解耦。

二、核心组件

组件 作用
Iterator 定义遍历接口(hasNext/next)
ConcreteIterator 实现具体集合的遍历逻辑
Aggregate 聚合对象接口,定义创建迭代器的方法
ConcreteAggregate 具体聚合对象,实现迭代器创建方法

三、模式优势

统一遍历接口:不同集合使用相同方式遍历
单一职责原则:分离集合管理与遍历算法
开闭原则:新增迭代器类型不影响现有代码
并行遍历:支持多个迭代器同时遍历集合

四、真实场景案例:社交网络关系遍历

场景需求
某社交平台需要实现:
用户关系包含 好友列表(数组存储)和 关注列表(链表存储)
需要统一接口遍历两种关系
支持 隐私过滤(不展示已注销用户)

五、Java实现代码

1. 迭代器接口

public interface RelationIterator<T> {
    boolean hasNext();
    T next();
    void remove();
}

2. 聚合对象接口

public interface SocialNetwork {
    RelationIterator<User> createIterator();
    RelationIterator<User> createActiveUserIterator(); // 扩展:过滤非活跃用户
}

3. 具体聚合对象实现

// 好友列表(数组存储)
class FriendList implements SocialNetwork {
    private User[] friends;
    private int size;

    public FriendList(int capacity) {
        friends = new User[capacity];
    }

    public void addFriend(User user) {
        if (size < friends.length) {
            friends[size++] = user;
        }
    }

    @Override
    public RelationIterator<User> createIterator() {
        return new FriendListIterator();
    }

    @Override
    public RelationIterator<User> createActiveUserIterator() {
        return new ActiveFriendListIterator();
    }

    // 具体迭代器实现(内部类)
    private class FriendListIterator implements RelationIterator<User> {
        private int position = 0;

        @Override
        public boolean hasNext() {
            return position < size;
        }

        @Override
        public User next() {
            if (!hasNext()) throw new NoSuchElementException();
            return friends[position++];
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    }

    // 扩展:过滤非活跃用户
    private class ActiveFriendListIterator implements RelationIterator<User> {
        private int position = 0;

        @Override
        public boolean hasNext() {
            skipInactiveUsers();
            return position < size;
        }

        @Override
        public User next() {
            if (!hasNext()) throw new NoSuchElementException();
            return friends[position++];
        }

        private void skipInactiveUsers() {
            while (position < size && !friends[position].isActive()) {
                position++;
            }
        }
    }
}

// 关注列表(链表存储)
class FollowingList implements SocialNetwork {
    private static class Node {
        User user;
        Node next;

        Node(User user) {
            this.user = user;
        }
    }

    private Node head;
    private Node tail;

    public void addFollowing(User user) {
        Node newNode = new Node(user);
        if (head == null) {
            head = tail = newNode;
        } else {
            tail.next = newNode;
            tail = newNode;
        }
    }

    @Override
    public RelationIterator<User> createIterator() {
        return new FollowingListIterator();
    }

    // 具体迭代器实现(内部类)
    private class FollowingListIterator implements RelationIterator<User> {
        private Node current = head;

        @Override
        public boolean hasNext() {
            return current != null;
        }

        @Override
        public User next() {
            if (!hasNext()) throw new NoSuchElementException();
            User user = current.user;
            current = current.next;
            return user;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    }
}

4. 用户实体类

public class User {
    private final String id;
    private String name;
    private boolean active = true;

    public User(String id, String name) {
        this.id = id;
        this.name = name;
    }

    // Getters/Setters
    public boolean isActive() { return active; }
    public void deactivate() { active = false; }
}

5. 客户端使用

public class SocialNetworkClient {
    public static void main(String[] args) {
        // 初始化数据
        User user1 = new User("U001", "张三");
        User user2 = new User("U002", "李四");
        user2.deactivate();
        User user3 = new User("U003", "王五");

        // 构建好友列表
        FriendList friends = new FriendList(10);
        friends.addFriend(user1);
        friends.addFriend(user2);
        friends.addFriend(user3);

        // 构建关注列表
        FollowingList followings = new FollowingList();
        followings.addFollowing(user3);
        followings.addFollowing(user1);

        // 遍历好友列表(基础迭代器)
        System.out.println("=== 好友列表 ===");
        printRelations(friends.createIterator());

        // 遍历关注列表
        System.out.println("\n=== 关注列表 ===");
        printRelations(followings.createIterator());

        // 使用过滤迭代器
        System.out.println("\n=== 活跃好友 ===");
        printRelations(friends.createActiveUserIterator());
    }

    private static void printRelations(RelationIterator<User> iterator) {
        while (iterator.hasNext()) {
            User user = iterator.next();
            System.out.printf("%s (%s)%n", user.getName(), user.isActive() ? "活跃" : "已注销");
        }
    }
}

六、运行结果

=== 好友列表 ===
张三 (活跃)
李四 (已注销)
王五 (活跃)

=== 关注列表 ===
王五 (活跃)
张三 (活跃)

=== 活跃好友 ===
张三 (活跃)
王五 (活跃)

七、模式变体与优化

1. 多维度迭代
// 组合条件迭代器
public interface CompositeIterator<T> extends RelationIterator<T> {
    void addFilter(Predicate<T> filter);
    void sort(Comparator<T> comparator);
}

// 使用示例
CompositeIterator<User> iterator = new SmartUserIterator();
iterator.addFilter(User::isVIP);
iterator.sort(Comparator.comparing(User::getJoinDate));
2. 线程安全实现
// 快照迭代器(避免ConcurrentModificationException)
public class SnapshotIterator<T> implements RelationIterator<T> {
    private final List<T> snapshot;
    private int position = 0;

    public SnapshotIterator(Collection<T> original) {
        this.snapshot = new ArrayList<>(original);
    }

    // 实现标准迭代器方法...
}

八、行业应用场景

场景 具体应用 优势体现
文件系统遍历 递归遍历目录结构 统一处理文件/文件夹
数据库查询 结果集游标遍历 处理海量数据内存优化
游戏物品系统 背包不同分类物品遍历 支持多种筛选条件
大数据处理 分片数据顺序访问 处理超出内存限制的数据
GUI组件树遍历 窗口组件层级遍历 支持深度优先/广度优先策略

九、最佳实践建议

迭代器生命周期管理
// 使用try-with-resources管理资源
try (RelationIterator<User> iterator = friends.createIterator()) {
    while (iterator.hasNext()) {
        // 处理逻辑
    }
}
空迭代器实现
// 空对象模式应用
public class EmptyIterator<T> implements RelationIterator<T> {
    @Override public boolean hasNext() { return false; }
    @Override public T next() { throw new NoSuchElementException(); }
}
性能优化技巧
// 预计算迭代路径(适用于树形结构)
public class PrecomputedTreeIterator<T> implements RelationIterator<T> {
    private final List<T> traversalPath;
    private int index = 0;
    
    public PrecomputedTreeIterator(TreeNode root) {
        this.traversalPath = preorderTraversal(root);
    }
    
    // 实现标准方法...
}

十、与相似模式对比

模式 核心差异 适用场景
迭代器 专注集合遍历机制 需要统一遍历接口的场景
访问者 在遍历过程中执行操作 对集合元素进行复杂操作
组合 处理树形结构 需要递归遍历的层级结构
工厂方法 用于创建迭代器对象 需要灵活创建不同类型迭代器

通过这个社交网络关系遍历的案例,可以看出迭代器模式如何 有效封装不同数据结构的遍历逻辑。在实际开发中,可根据需求扩展迭代器功能(如过滤、排序、分页等),同时保持客户端代码的简洁性。该模式特别适合需要支持多种数据存储方式且需要统一访问接口的系统架构。

一句话总结

迭代器模式是为了提供一种能顺序遍历对象的解决方案,该方案不对外暴露存储细节。