Java案例怎么实现迭代器模式?

wen java案例 44

Java迭代器模式实现案例

迭代器模式用于提供一种顺序访问聚合对象元素的方法,而不暴露其内部表示,以下是几种常见实现方式:

Java案例怎么实现迭代器模式?

基础迭代器模式实现

// 1. 迭代器接口
interface Iterator<T> {
    boolean hasNext();
    T next();
}
// 2. 聚合接口
interface Aggregate<T> {
    Iterator<T> createIterator();
}
// 3. 具体聚合类
class BookCollection implements Aggregate<Book> {
    private Book[] books;
    private int index = 0;
    public BookCollection(int size) {
        books = new Book[size];
    }
    public void addBook(Book book) {
        if (index < books.length) {
            books[index++] = book;
        }
    }
    public Book getBook(int index) {
        return books[index];
    }
    public int getSize() {
        return books.length;
    }
    @Override
    public Iterator<Book> createIterator() {
        return new BookIterator(this);
    }
}
// 4. 具体迭代器类
class BookIterator implements Iterator<Book> {
    private BookCollection collection;
    private int index = 0;
    public BookIterator(BookCollection collection) {
        this.collection = collection;
    }
    @Override
    public boolean hasNext() {
        return index < collection.getSize() && 
               collection.getBook(index) != null;
    }
    @Override
    public Book next() {
        return collection.getBook(index++);
    }
}
// 5. 元素类
class Book {
    private String title;
    private String author;
    public Book(String title, String author) {
        this.title = title;
        this.author = author;
    }
    @Override
    public String toString() {
        return "《" + title + "》 by " + author;
    }
}
// 6. 客户端使用
public class IteratorPatternDemo {
    public static void main(String[] args) {
        BookCollection collection = new BookCollection(5);
        collection.addBook(new Book("Java编程思想", "Bruce Eckel"));
        collection.addBook(new Book("设计模式", "GoF"));
        collection.addBook(new Book("重构", "Martin Fowler"));
        Iterator<Book> iterator = collection.createIterator();
        System.out.println("遍历书籍集合:");
        while (iterator.hasNext()) {
            Book book = iterator.next();
            System.out.println(book);
        }
    }
}

使用Java内置迭代器实现

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class BuiltInIteratorExample {
    public static void main(String[] args) {
        // 使用ArrayList(实现了Iterable)
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");
        // 方式1: 使用for-each(隐式使用迭代器)
        System.out.println("方式1: for-each循环");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
        // 方式2: 显式使用迭代器
        System.out.println("\n方式2: 显式迭代器");
        Iterator<String> iterator = fruits.iterator();
        while (iterator.hasNext()) {
            String fruit = iterator.next();
            System.out.println(fruit);
        }
        // 方式3: 使用Java 8的forEach
        System.out.println("\n方式3: Java 8 forEach");
        fruits.forEach(System.out::println);
    }
}

自定义列表迭代器实现

import java.util.Iterator;
// 自定义列表类实现Iterable接口
class CustomList<T> implements Iterable<T> {
    private Object[] elements;
    private int size = 0;
    private static final int DEFAULT_CAPACITY = 10;
    public CustomList() {
        elements = new Object[DEFAULT_CAPACITY];
    }
    public void add(T element) {
        if (size == elements.length) {
            resize();
        }
        elements[size++] = element;
    }
    private void resize() {
        Object[] newArray = new Object[elements.length * 2];
        System.arraycopy(elements, 0, newArray, 0, elements.length);
        elements = newArray;
    }
    @SuppressWarnings("unchecked")
    public T get(int index) {
        if (index >= size || index < 0) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
        }
        return (T) elements[index];
    }
    public int size() {
        return size;
    }
    @Override
    public Iterator<T> iterator() {
        return new CustomIterator();
    }
    // 内部迭代器类
    private class CustomIterator implements Iterator<T> {
        private int currentIndex = 0;
        @Override
        public boolean hasNext() {
            return currentIndex < size;
        }
        @Override
        @SuppressWarnings("unchecked")
        public T next() {
            if (!hasNext()) {
                throw new java.util.NoSuchElementException();
            }
            return (T) elements[currentIndex++];
        }
        @Override
        public void remove() {
            throw new UnsupportedOperationException("remove not supported");
        }
    }
}
// 测试类
public class CustomListDemo {
    public static void main(String[] args) {
        CustomList<Integer> numbers = new CustomList<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(4);
        numbers.add(5);
        System.out.println("遍历自定义列表:");
        for (Integer num : numbers) {
            System.out.println(num);
        }
    }
}

支持多种遍历方式的迭代器

import java.util.Iterator;
import java.util.NoSuchElementException;
// 树节点类
class TreeNode<T> {
    T data;
    TreeNode<T> left;
    TreeNode<T> right;
    public TreeNode(T data) {
        this.data = data;
    }
}
// 二叉树类,支持多种遍历方式
class BinaryTree<T> implements Iterable<T> {
    private TreeNode<T> root;
    public BinaryTree(TreeNode<T> root) {
        this.root = root;
    }
    // 前序遍历迭代器
    public Iterator<T> preOrderIterator() {
        return new PreOrderIterator(root);
    }
    // 中序遍历迭代器
    public Iterator<T> inOrderIterator() {
        return new InOrderIterator(root);
    }
    // 后序遍历迭代器
    public Iterator<T> postOrderIterator() {
        return new PostOrderIterator(root);
    }
    // 默认实现前序遍历
    @Override
    public Iterator<T> iterator() {
        return preOrderIterator();
    }
    // 前序遍历迭代器实现
    private class PreOrderIterator implements Iterator<T> {
        private java.util.Stack<TreeNode<T>> stack = new java.util.Stack<>();
        public PreOrderIterator(TreeNode<T> root) {
            if (root != null) {
                stack.push(root);
            }
        }
        @Override
        public boolean hasNext() {
            return !stack.isEmpty();
        }
        @Override
        public T next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            TreeNode<T> node = stack.pop();
            if (node.right != null) {
                stack.push(node.right);
            }
            if (node.left != null) {
                stack.push(node.left);
            }
            return node.data;
        }
    }
    // 中序遍历迭代器实现
    private class InOrderIterator implements Iterator<T> {
        private java.util.Stack<TreeNode<T>> stack = new java.util.Stack<>();
        private TreeNode<T> current;
        public InOrderIterator(TreeNode<T> root) {
            current = root;
        }
        @Override
        public boolean hasNext() {
            return !stack.isEmpty() || current != null;
        }
        @Override
        public T next() {
            while (current != null) {
                stack.push(current);
                current = current.left;
            }
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            TreeNode<T> node = stack.pop();
            current = node.right;
            return node.data;
        }
    }
    // 后序遍历迭代器实现
    private class PostOrderIterator implements Iterator<T> {
        private java.util.Stack<TreeNode<T>> stack1 = new java.util.Stack<>();
        private java.util.Stack<TreeNode<T>> stack2 = new java.util.Stack<>();
        public PostOrderIterator(TreeNode<T> root) {
            if (root != null) {
                stack1.push(root);
                while (!stack1.isEmpty()) {
                    TreeNode<T> node = stack1.pop();
                    stack2.push(node);
                    if (node.left != null) {
                        stack1.push(node.left);
                    }
                    if (node.right != null) {
                        stack1.push(node.right);
                    }
                }
            }
        }
        @Override
        public boolean hasNext() {
            return !stack2.isEmpty();
        }
        @Override
        public T next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            return stack2.pop().data;
        }
    }
}
// 测试类
public class TreeIteratorDemo {
    public static void main(String[] args) {
        // 构建二叉树
        TreeNode<Integer> root = new TreeNode<>(1);
        root.left = new TreeNode<>(2);
        root.right = new TreeNode<>(3);
        root.left.left = new TreeNode<>(4);
        root.left.right = new TreeNode<>(5);
        root.right.left = new TreeNode<>(6);
        root.right.right = new TreeNode<>(7);
        BinaryTree<Integer> tree = new BinaryTree<>(root);
        System.out.println("前序遍历:");
        Iterator<Integer> preOrder = tree.preOrderIterator();
        while (preOrder.hasNext()) {
            System.out.print(preOrder.next() + " ");
        }
        System.out.println();
        System.out.println("中序遍历:");
        Iterator<Integer> inOrder = tree.inOrderIterator();
        while (inOrder.hasNext()) {
            System.out.print(inOrder.next() + " ");
        }
        System.out.println();
        System.out.println("后序遍历:");
        Iterator<Integer> postOrder = tree.postOrderIterator();
        while (postOrder.hasNext()) {
            System.out.print(postOrder.next() + " ");
        }
        System.out.println();
    }
}

支持过滤和转换的迭代器

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.Function;
import java.util.function.Predicate;
// 高级迭代器工具类
class IteratorUtils {
    // 过滤迭代器
    public static <T> Iterator<T> filter(Iterator<T> source, Predicate<T> predicate) {
        return new Iterator<T>() {
            private T nextItem = null;
            private boolean hasNextCalled = false;
            private void findNext() {
                while (source.hasNext()) {
                    T item = source.next();
                    if (predicate.test(item)) {
                        nextItem = item;
                        return;
                    }
                }
                nextItem = null;
            }
            @Override
            public boolean hasNext() {
                if (!hasNextCalled) {
                    findNext();
                    hasNextCalled = true;
                }
                return nextItem != null;
            }
            @Override
            public T next() {
                if (!hasNext()) {
                    throw new NoSuchElementException();
                }
                hasNextCalled = false;
                return nextItem;
            }
        };
    }
    // 转换迭代器
    public static <T, R> Iterator<R> map(Iterator<T> source, Function<T, R> mapper) {
        return new Iterator<R>() {
            @Override
            public boolean hasNext() {
                return source.hasNext();
            }
            @Override
            public R next() {
                return mapper.apply(source.next());
            }
        };
    }
    // 限制数量迭代器
    public static <T> Iterator<T> limit(Iterator<T> source, int maxSize) {
        return new Iterator<T>() {
            private int count = 0;
            @Override
            public boolean hasNext() {
                return count < maxSize && source.hasNext();
            }
            @Override
            public T next() {
                if (!hasNext()) {
                    throw new NoSuchElementException();
                }
                count++;
                return source.next();
            }
        };
    }
}
// 测试类
public class AdvancedIteratorDemo {
    public static void main(String[] args) {
        java.util.List<Integer> numbers = java.util.Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        System.out.println("原始数据:");
        numbers.forEach(n -> System.out.print(n + " "));
        System.out.println();
        // 过滤出偶数
        Iterator<Integer> evenIterator = IteratorUtils.filter(
            numbers.iterator(), 
            n -> n % 2 == 0
        );
        System.out.println("偶数:");
        while (evenIterator.hasNext()) {
            System.out.print(evenIterator.next() + " ");
        }
        System.out.println();
        // 转换
        Iterator<String> stringIterator = IteratorUtils.map(
            numbers.iterator(),
            n -> "Number: " + n
        );
        System.out.println("转换后:");
        while (stringIterator.hasNext()) {
            System.out.print(stringIterator.next() + " ");
        }
        System.out.println();
        // 组合使用
        Iterator<Integer> combined = IteratorUtils.limit(
            IteratorUtils.filter(numbers.iterator(), n -> n > 5),
            3
        );
        System.out.println("组合操作 (过滤大于5,取前3个):");
        while (combined.hasNext()) {
            System.out.print(combined.next() + " ");
        }
        System.out.println();
    }
}
  1. 核心角色

    • Iterator(迭代器接口)
    • ConcreteIterator(具体迭代器)
    • Aggregate(聚合接口)
    • ConcreteAggregate(具体聚合)
  2. 实现方式

    • 自定义迭代器
    • 使用Java内置的Iterable和Iterator
    • 支持多种遍历策略
  3. 应用场景

    • 需要统一遍历不同聚合结构
    • 需要提供多种遍历方式
    • 需要在不暴露内部结构的情况下访问元素
  4. 优势

    • 简化聚合类的接口
    • 支持多种遍历方式
    • 可以并行遍历同一个集合
    • 延迟加载和惰性求值

抱歉,评论功能暂时关闭!