一、模式定義
迭代器模式(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;}}@Overridepublic RelationIterator<User> createIterator() {return new FriendListIterator();}@Overridepublic RelationIterator<User> createActiveUserIterator() {return new ActiveFriendListIterator();}// 具體迭代器實現(內部類)private class FriendListIterator implements RelationIterator<User> {private int position = 0;@Overridepublic boolean hasNext() {return position < size;}@Overridepublic User next() {if (!hasNext()) throw new NoSuchElementException();return friends[position++];}@Overridepublic void remove() {throw new UnsupportedOperationException();}}// 擴展:過濾非活躍用戶private class ActiveFriendListIterator implements RelationIterator<User> {private int position = 0;@Overridepublic boolean hasNext() {skipInactiveUsers();return position < size;}@Overridepublic 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;}}@Overridepublic RelationIterator<User> createIterator() {return new FollowingListIterator();}// 具體迭代器實現(內部類)private class FollowingListIterator implements RelationIterator<User> {private Node current = head;@Overridepublic boolean hasNext() {return current != null;}@Overridepublic User next() {if (!hasNext()) throw new NoSuchElementException();User user = current.user;current = current.next;return user;}@Overridepublic 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/Setterspublic 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);}// 實現標準方法...
}
十、與相似模式對比
模式 | 核心差異 | 適用場景 |
---|---|---|
迭代器 | 專注集合遍歷機制 | 需要統一遍歷接口的場景 |
訪問者 | 在遍歷過程中執行操作 | 對集合元素進行復雜操作 |
組合 | 處理樹形結構 | 需要遞歸遍歷的層級結構 |
工廠方法 | 用于創建迭代器對象 | 需要靈活創建不同類型迭代器 |
通過這個社交網絡關系遍歷的案例,可以看出迭代器模式如何 有效封裝不同數據結構的遍歷邏輯。在實際開發中,可根據需求擴展迭代器功能(如過濾、排序、分頁等),同時保持客戶端代碼的簡潔性。該模式特別適合需要支持多種數據存儲方式且需要統一訪問接口的系統架構。
一句話總結
迭代器模式是為了提供一種能順序遍歷對象的解決方案,該方案不對外暴露存儲細節。