设计模式-14迭代器模式Iterator Pattern

迭代器模式(Iterator Pattern)详解 迭代器模式是一种行为型设计模式,它提供一种方法来顺序访问一个聚合对象中的各个元素,而不需要暴露该对象的内部表示。迭代器模式将遍历元素的责任从聚合对象转移到迭代器对象上,简化了聚合类,并使得可以用不同的方式遍历一个聚合对象。迭代器模式的核心思想是:“提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露该对象的内部表示。”在以下情况下,迭代器模式特别有用:如果不使用迭代器模式,客户端代码可能需要了解并处理不同集合类的内部结构,导致代码复杂度增加,且难以适应集合结构的变化。使用迭代器模式可以将这些复杂性隐藏起 阅读详情

迭代器模式 (Iterator Pattern)

概述 (Overview)

迭代器模式是一种行为型设计模式,它提供了一种方法顺序访问一个聚合对象中的各个元素,而又不暴露其内部的表示。

Iterator Pattern is a behavioral design pattern that provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

意图 (Intent)

提供一种方法顺序访问一个聚合对象中的各个元素,而又不需暴露该对象的内部表示。

Provide a way to access the elements of an aggregate object sequentially without exposing the underlying representation.

适用场景 (When to Use)

  • 当需要访问一个聚合对象的内容而又不暴露其内部表示时
  • 当需要为聚合对象提供多种遍历方式时
  • 当需要为遍历不同的聚合结构提供一个统一的接口时
  • 当需要在不修改聚合类的情况下增加新的遍历操作时
  • 当需要支持多个同时进行的遍历时

结构 (Structure)

基础迭代器模式结构图 (Basic Iterator Pattern Structure)

uses
uses
«interface»
Iterator
+hasNext()
+next()
+remove()
ConcreteIterator
-collection: ConcreteAggregate
-currentIndex: int
+hasNext()
+next()
+remove()
«interface»
Aggregate
+createIterator()
ConcreteAggregate
-items: Object[]
+createIterator()
+getItems()
+getSize()
Client
+traverseCollection()

实现方式 (Implementation Approaches)

1. 经典迭代器模式 (Classic Iterator Pattern)

// 迭代器接口 - Iterator Interface
public interface Iterator<T> {
    boolean hasNext();
    T next();
    void remove();
}

// 具体迭代器 - Concrete Iterator
public class BookIterator implements Iterator<Book> {
    private BookCollection collection;
    private int currentIndex = 0;
    
    public BookIterator(BookCollection collection) {
        this.collection = collection;
    }
    
    @Override
    public boolean hasNext() {
        return currentIndex < collection.getSize();
    }
    
    @Override
    public Book next() {
        if (!hasNext()) {
            throw new NoSuchElementException("没有更多元素了");
        }
        return collection.getBook(currentIndex++);
    }
    
    @Override
    public void remove() {
        if (currentIndex <= 0) {
            throw new IllegalStateException("无法删除,尚未调用next()或已删除");
        }
        collection.removeBook(--currentIndex);
    }
}

// 聚合接口 - Aggregate Interface
public interface Aggregate<T> {
    Iterator<T> createIterator();
}

// 书籍类 - Book Class
public class Book {
    private String isbn;
    private String title;
    private String author;
    private double price;
    
    public Book(String isbn, String title, String author, double price) {
        this.isbn = isbn;
        this.title = title;
        this.author = author;
        this.price = price;
    }
    
    // Getters
    public String getIsbn() { return isbn; }
    public String getTitle() { return title; }
    public String getAuthor() { return author; }
    public double getPrice() { return price; }
    
    @Override
    public String toString() {
        return String.format("《%s》- %s (ISBN: %s) ¥%.2f", title, author, isbn, price);
    }
}

// 书籍集合 - Book Collection
public class BookCollection implements Aggregate<Book> {
    private List<Book> books;
    
    public BookCollection() {
        this.books = new ArrayList<>();
    }
    
    public void addBook(Book book) {
        books.add(book);
    }
    
    public void removeBook(int index) {
        if (index >= 0 && index < books.size()) {
            books.remove(index);
        }
    }
    
    public Book getBook(int index) {
        if (index >= 0 && index < books.size()) {
            return books.get(index);
        }
        throw new IndexOutOfBoundsException("索引超出范围");
    }
    
    public int getSize() {
        return books.size();
    }
    
    @Override
    public Iterator<Book> createIterator() {
        return new BookIterator(this);
    }
    
    public List<Book> getBooks() {
        return new ArrayList<>(books);
    }
}

// 客户端使用 - Client Usage
public class BookstoreSystem {
    public static void main(String[] args) {
        System.out.println("=== 书店系统迭代器模式演示 ===");
        
        // 创建书籍集合
        BookCollection collection = new BookCollection();
        
        // 添加书籍
        collection.addBook(new Book("978-7-111-54321-0", "Java编程思想", "Bruce Eckel", 108.00));
        collection.addBook(new Book("978-7-111-12345-6", "设计模式", "Gang of Four", 89.00));
        collection.addBook(new Book("978-7-111-98765-4", "Spring实战", "Craig Walls", 99.00));
        collection.addBook(new Book("978-7-111-55555-5", "MyBatis技术内幕", "徐郡明", 79.00));
        collection.addBook(new Book("978-7-111-66666-6", "Netty权威指南", "李林锋", 118.00));
        
        // 使用迭代器遍历
        System.out.println("\n--- 使用迭代器遍历书籍 ---");
        Iterator<Book> iterator = collection.createIterator();
        while (iterator.hasNext()) {
            Book book = iterator.next();
            System.out.println(book);
        }
        
        // 测试删除功能
        System.out.println("\n--- 测试删除功能 ---");
        iterator = collection.createIterator();
        if (iterator.hasNext()) {
            iterator.next(); // 移动到第一个元素
            iterator.remove(); // 删除第一个元素
            System.out.println("已删除第一本书");
        }
        
        System.out.println("\n--- 删除后的书籍列表 ---");
        iterator = collection.createIterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
        
        System.out.println("当前书籍数量: " + collection.getSize());
    }
}

2. 反向迭代器模式 (Reverse Iterator Pattern)

// 反向迭代器接口 - Reverse Iterator Interface
public interface ReverseIterator<T> extends Iterator<T> {
    boolean hasPrevious();
    T previous();
    void reset();
}

// 具体反向迭代器 - Concrete Reverse Iterator
public class ReverseBookIterator implements ReverseIterator<Book> {
    private BookCollection collection;
    private int currentIndex;
    
    public ReverseBookIterator(BookCollection collection) {
        this.collection = collection;
        this.currentIndex = collection.getSize() - 1;
    }
    
    @Override
    public boolean hasNext() {
        return currentIndex >= 0;
    }
    
    @Override
    public Book next() {
        if (!hasNext()) {
            throw new NoSuchElementException("没有更多元素了");
        }
        return collection.getBook(currentIndex--);
    }
    
    @Override
    public boolean hasPrevious() {
        return currentIndex < collection.getSize() - 1;
    }
    
    @Override
    public Book previous() {
        if (!hasPrevious()) {
            throw new NoSuchElementException("没有前一个元素了");
        }
        return collection.getBook(++currentIndex);
    }
    
    @Override
    public void remove() {
        if (currentIndex >= collection.getSize() - 1) {
            throw new IllegalStateException("无法删除,尚未调用next()");
        }
        collection.removeBook(currentIndex + 1);
    }
    
    @Override
    public void reset() {
        currentIndex = collection.getSize() - 1;
    }
}

// 支持反向迭代的聚合接口 - Aggregate Interface with Reverse Iterator
public interface ReversibleAggregate<T> extends Aggregate<T> {
    ReverseIterator<T> createReverseIterator();
}

// 支持反向迭代的书籍集合 - Book Collection with Reverse Iterator
public class ReversibleBookCollection extends BookCollection implements ReversibleAggregate<Book> {
    
    @Override
    public ReverseIterator<Book> createReverseIterator() {
        return new ReverseBookIterator(this);
    }
}

// 客户端使用 - Client Usage
public class ReverseIteratorDemo {
    public static void main(String[] args) {
        System.out.println("=== 反向迭代器模式演示 ===");
        
        ReversibleBookCollection collection = new ReversibleBookCollection();
        
        // 添加书籍
        collection.addBook(new Book("978-7-111-11111-1", "Java核心技术", "Cay Horstmann", 128.00));
        collection.addBook(new Book("978-7-111-22222-2", "Effective Java", "Joshua Bloch", 89.00));
        collection.addBook(new Book("978-7-111-33333-3", "Java并发编程实战", "Brian Goetz", 99.00));
        collection.addBook(new Book("978-7-111-44444-4", "深入理解Java虚拟机", "周志明", 79.00));
        
        System.out.println("\n--- 正向遍历 ---");
        Iterator<Book> forwardIterator = collection.createIterator();
        while (forwardIterator.hasNext()) {
            System.out.println(forwardIterator.next());
        }
        
        System.out.println("\n--- 反向遍历 ---");
        ReverseIterator<Book> reverseIterator = collection.createReverseIterator();
        while (reverseIterator.hasNext()) {
            System.out.println(reverseIterator.next());
        }
        
        System.out.println("\n--- 双向遍历演示 ---");
        reverseIterator = collection.createReverseIterator();
        System.out.println("反向遍历前两个元素:");
        if (reverseIterator.hasNext()) System.out.println(reverseIterator.next());
        if (reverseIterator.hasNext()) System.out.println(reverseIterator.next());
        
        System.out.println("\n正向回退一个元素:");
        if (reverseIterator.hasPrevious()) System.out.println(reverseIterator.previous());
    }
}

3. 过滤迭代器模式 (Filter Iterator Pattern)

// 过滤条件接口 - Filter Condition Interface
public interface FilterCondition<T> {
    boolean matches(T item);
}

// 价格过滤条件 - Price Filter Condition
public class PriceFilter implements FilterCondition<Book> {
    private double minPrice;
    private double maxPrice;
    
    public PriceFilter(double minPrice, double maxPrice) {
        this.minPrice = minPrice;
        this.maxPrice = maxPrice;
    }
    
    @Override
    public boolean matches(Book book) {
        return book.getPrice() >= minPrice && book.getPrice() <= maxPrice;
    }
}

// 作者过滤条件 - Author Filter Condition
public class AuthorFilter implements FilterCondition<Book> {
    private String authorKeyword;
    
    public AuthorFilter(String authorKeyword) {
        this.authorKeyword = authorKeyword.toLowerCase();
    }
    
    @Override
    public boolean matches(Book book) {
        return book.getAuthor().toLowerCase().contains(authorKeyword);
    }
}

// 复合过滤条件 - Composite Filter Condition
public class CompositeFilter<T> implements FilterCondition<T> {
    private List<FilterCondition<T>> conditions;
    private boolean requireAll; // true=AND, false=OR
    
    public CompositeFilter(boolean requireAll) {
        this.conditions = new ArrayList<>();
        this.requireAll = requireAll;
    }
    
    public void addCondition(FilterCondition<T> condition) {
        conditions.add(condition);
    }
    
    @Override
    public boolean matches(T item) {
        if (conditions.isEmpty()) return true;
        
        if (requireAll) {
            // AND逻辑:所有条件都必须匹配
            return conditions.stream().allMatch(condition -> condition.matches(item));
        } else {
            // OR逻辑:至少一个条件匹配
            return conditions.stream().anyMatch(condition -> condition.matches(item));
        }
    }
}

// 过滤迭代器 - Filter Iterator
public class FilterIterator<T> implements Iterator<T> {
    private Iterator<T> originalIterator;
    private FilterCondition<T> condition;
    private T nextElement;
    private boolean hasNextElement;
    
    public FilterIterator(Iterator<T> originalIterator, FilterCondition<T> condition) {
        this.originalIterator = originalIterator;
        this.condition = condition;
        advanceToNext();
    }
    
    private void advanceToNext() {
        hasNextElement = false;
        nextElement = null;
        
        while (originalIterator.hasNext()) {
            T element = originalIterator.next();
            if (condition.matches(element)) {
                nextElement = element;
                hasNextElement = true;
                break;
            }
        }
    }
    
    @Override
    public boolean hasNext() {
        return hasNextElement;
    }
    
    @Override
    public T next() {
        if (!hasNextElement) {
            throw new NoSuchElementException("没有更多匹配的元素");
        }
        T result = nextElement;
        advanceToNext();
        return result;
    }
    
    @Override
    public void remove() {
        throw new UnsupportedOperationException("过滤迭代器不支持删除操作");
    }
}

// 支持过滤的聚合 - Filterable Aggregate
public interface FilterableAggregate<T> extends Aggregate<T> {
    Iterator<T> createFilteredIterator(FilterCondition<T> condition);
}

// 支持过滤的书籍集合 - Filterable Book Collection
public class FilterableBookCollection extends BookCollection implements FilterableAggregate<Book> {
    
    @Override
    public Iterator<Book> createFilteredIterator(FilterCondition<Book> condition) {
        return new FilterIterator<>(createIterator(), condition);
    }
}

// 客户端使用 - Client Usage
public class FilterIteratorDemo {
    public static void main(String[] args) {
        System.out.println("=== 过滤迭代器模式演示 ===");
        
        FilterableBookCollection collection = new FilterableBookCollection();
        
        // 添加书籍
        collection.addBook(new Book("978-7-111-10001-1", "Java基础教程", "张三", 45.00));
        collection.addBook(new Book("978-7-111-10002-2", "Java高级编程", "李四", 89.00));
        collection.addBook(new Book("978-7-111-10003-3", "Spring实战", "王五", 99.00));
        collection.addBook(new Book("978-7-111-10004-4", "MyBatis入门", "赵六", 55.00));
        collection.addBook(new Book("978-7-111-10005-5", "Netty权威指南", "钱七", 118.00));
        collection.addBook(new Book("978-7-111-10006-6", "Java并发编程", "孙八", 79.00));
        
        System.out.println("\n--- 价格过滤:50-100元的书籍 ---");
        FilterCondition<Book> priceFilter = new PriceFilter(50, 100);
        Iterator<Book> priceFilteredIterator = collection.createFilteredIterator(priceFilter);
        while (priceFilteredIterator.hasNext()) {
            System.out.println(priceFilteredIterator.next());
        }
        
        System.out.println("\n--- 作者过滤:包含'Java'的作者 ---");
        FilterCondition<Book> authorFilter = new AuthorFilter("Java");
        Iterator<Book> authorFilteredIterator = collection.createFilteredIterator(authorFilter);
        while (authorFilteredIterator.hasNext()) {
            System.out.println(authorFilteredIterator.next());
        }
        
        System.out.println("\n--- 复合过滤:价格50-100元 AND 作者包含'Java' ---");
        CompositeFilter<Book> compositeFilter = new CompositeFilter<>(true); // AND逻辑
        compositeFilter.addCondition(priceFilter);
        compositeFilter.addCondition(authorFilter);
        
        Iterator<Book> compositeFilteredIterator = collection.createFilteredIterator(compositeFilter);
        while (compositeFilteredIterator.hasNext()) {
            System.out.println(compositeFilteredIterator.next());
        }
        
        System.out.println("\n--- 复合过滤:价格50-100元 OR 作者包含'Java' ---");
        CompositeFilter<Book> orFilter = new CompositeFilter<>(false); // OR逻辑
        orFilter.addCondition(priceFilter);
        orFilter.addCondition(authorFilter);
        
        Iterator<Book> orFilteredIterator = collection.createFilteredIterator(orFilter);
        while (orFilteredIterator.hasNext()) {
            System.out.println(orFilteredIterator.next());
        }
    }
}

框架源码中的应用 (Framework Applications)

1. Java Collections Framework

// Java集合框架中的迭代器模式应用
// Java Collections Framework Iterator Pattern Application

// 自定义列表迭代器 - Custom List Iterator
public class CustomArrayList<T> implements Iterable<T> {
    private static final int DEFAULT_CAPACITY = 10;
    private Object[] elements;
    private int size;
    
    public CustomArrayList() {
        this.elements = new Object[DEFAULT_CAPACITY];
        this.size = 0;
    }
    
    public void add(T element) {
        ensureCapacity();
        elements[size++] = element;
    }
    
    public T get(int index) {
        checkIndex(index);
        return (T) elements[index];
    }
    
    public void remove(int index) {
        checkIndex(index);
        System.arraycopy(elements, index + 1, elements, index, size - index - 1);
        elements[--size] = null;
    }
    
    public int size() {
        return size;
    }
    
    public boolean isEmpty() {
        return size == 0;
    }
    
    private void ensureCapacity() {
        if (size == elements.length) {
            elements = Arrays.copyOf(elements, elements.length * 2);
        }
    }
    
    private void checkIndex(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
        }
    }
    
    @Override
    public Iterator<T> iterator() {
        return new CustomIterator();
    }
    
    // 自定义迭代器 - Custom Iterator
    private class CustomIterator implements Iterator<T> {
        private int currentIndex = 0;
        private int lastReturnedIndex = -1;
        
        @Override
        public boolean hasNext() {
            return currentIndex < size;
        }
        
        @Override
        public T next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            lastReturnedIndex = currentIndex;
            return (T) elements[currentIndex++];
        }
        
        @Override
        public void remove() {
            if (lastReturnedIndex < 0) {
                throw new IllegalStateException();
            }
            CustomArrayList.this.remove(lastReturnedIndex);
            currentIndex = lastReturnedIndex;
            lastReturnedIndex = -1;
        }
    }
    
    // 反向迭代器 - Reverse Iterator
    public Iterator<T> reverseIterator() {
        return new ReverseIterator();
    }
    
    private class ReverseIterator implements Iterator<T> {
        private int currentIndex = size - 1;
        private int lastReturnedIndex = -1;
        
        @Override
        public boolean hasNext() {
            return currentIndex >= 0;
        }
        
        @Override
        public T next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            lastReturnedIndex = currentIndex;
            return (T) elements[currentIndex--];
        }
        
        @Override
        public void remove() {
            if (lastReturnedIndex < 0) {
                throw new IllegalStateException();
            }
            CustomArrayList.this.remove(lastReturnedIndex);
            currentIndex = lastReturnedIndex - 1;
            lastReturnedIndex = -1;
        }
    }
}

// 客户端使用 - Client Usage
public class CustomCollectionDemo {
    public static void main(String[] args) {
        System.out.println("=== 自定义集合迭代器模式演示 ===");
        
        CustomArrayList<String> list = new CustomArrayList<>();
        
        // 添加元素
        list.add("Java");
        list.add("Python");
        list.add("JavaScript");
        list.add("C++");
        list.add("Go");
        
        System.out.println("\n--- 正向遍历 ---");
        for (String language : list) {
            System.out.println(language);
        }
        
        System.out.println("\n--- 反向遍历 ---");
        Iterator<String> reverseIterator = list.reverseIterator();
        while (reverseIterator.hasNext()) {
            System.out.println(reverseIterator.next());
        }
        
        System.out.println("\n--- 使用迭代器删除元素 ---");
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            String language = iterator.next();
            if (language.startsWith("Java")) {
                iterator.remove();
                System.out.println("删除: " + language);
            }
        }
        
        System.out.println("\n--- 删除后的列表 ---");
        for (String language : list) {
            System.out.println(language);
        }
    }
}

2. Spring Data JPA - Repository接口

// Spring Data JPA中的迭代器模式应用
// Spring Data JPA Repository Iterator Pattern Application

// 实体类 - Entity Class
@Entity
@Table(name = "products")
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(name = "name")
    private String name;
    
    @Column(name = "price")
    private BigDecimal price;
    
    @Column(name = "category")
    private String category;
    
    @Column(name = "stock_quantity")
    private int stockQuantity;
    
    // 构造函数、getters和setters
    public Product() {}
    
    public Product(String name, BigDecimal price, String category, int stockQuantity) {
        this.name = name;
        this.price = price;
        this.category = category;
        this.stockQuantity = stockQuantity;
    }
    
    // Getters and setters
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public BigDecimal getPrice() { return price; }
    public void setPrice(BigDecimal price) { this.price = price; }
    public String getCategory() { return category; }
    public void setCategory(String category) { this.category = category; }
    public int getStockQuantity() { return stockQuantity; }
    public void setStockQuantity(int stockQuantity) { this.stockQuantity = stockQuantity; }
    
    @Override
    public String toString() {
        return String.format("Product{id=%d, name='%s', price=%s, category='%s', stock=%d}", 
                           id, name, price, category, stockQuantity);
    }
}

// 自定义Repository接口 - Custom Repository Interface
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
    
    // 基于方法名称的查询
    List<Product> findByCategory(String category);
    List<Product> findByPriceBetween(BigDecimal minPrice, BigDecimal maxPrice);
    List<Product> findByStockQuantityGreaterThan(int quantity);
    
    // 使用@Query注解的自定义查询
    @Query("SELECT p FROM Product p WHERE p.category = :category AND p.price <= :maxPrice")
    List<Product> findByCategoryAndMaxPrice(@Param("category") String category, @Param("maxPrice") BigDecimal maxPrice);
    
    // 使用原生SQL查询
    @Query(value = "SELECT * FROM products WHERE stock_quantity < :threshold", nativeQuery = true)
    List<Product> findLowStockProducts(@Param("threshold") int threshold);
    
    // 返回Stream的查询方法
    @Query("SELECT p FROM Product p WHERE p.price >= :minPrice")
    Stream<Product> streamByMinPrice(@Param("minPrice") BigDecimal minPrice);
    
    // 分页查询
    Page<Product> findByCategoryOrderByPriceDesc(String category, Pageable pageable);
}

// 自定义产品迭代器 - Custom Product Iterator
@Component
public class ProductIterator implements Iterator<Product> {
    private final ProductRepository productRepository;
    private Iterator<Product> currentIterator;
    private String currentCategory;
    private BigDecimal currentMinPrice;
    private int batchSize = 100;
    private int currentPage = 0;
    private boolean hasMoreData = true;
    
    public ProductIterator(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }
    
    public ProductIterator byCategory(String category) {
        this.currentCategory = category;
        loadNextBatch();
        return this;
    }
    
    public ProductIterator byMinPrice(BigDecimal minPrice) {
        this.currentMinPrice = minPrice;
        loadNextBatch();
        return this;
    }
    
    private void loadNextBatch() {
        if (!hasMoreData) return;
        
        Pageable pageable = PageRequest.of(currentPage++, batchSize);
        Page<Product> page;
        
        if (currentCategory != null) {
            page = productRepository.findByCategoryOrderByPriceDesc(currentCategory, pageable);
        } else if (currentMinPrice != null) {
            List<Product> products = productRepository.findByPriceBetween(currentMinPrice, new BigDecimal("999999"));
            currentIterator = products.iterator();
            hasMoreData = false;
            return;
        } else {
            page = productRepository.findAll(pageable);
        }
        
        currentIterator = page.getContent().iterator();
        hasMoreData = page.hasNext();
    }
    
    @Override
    public boolean hasNext() {
        if (currentIterator == null) return false;
        
        if (!currentIterator.hasNext() && hasMoreData) {
            loadNextBatch();
        }
        
        return currentIterator.hasNext();
    }
    
    @Override
    public Product next() {
        if (!hasNext()) {
            throw new NoSuchElementException("没有更多产品了");
        }
        return currentIterator.next();
    }
}

// 产品服务类 - Product Service
@Service
public class ProductService {
    private final ProductRepository productRepository;
    private final ProductIterator productIterator;
    
    @Autowired
    public ProductService(ProductRepository productRepository, ProductIterator productIterator) {
        this.productRepository = productRepository;
        this.productIterator = productIterator;
    }
    
    // 使用Stream API处理产品数据
    @Transactional(readOnly = true)
    public void processExpensiveProducts(BigDecimal minPrice) {
        System.out.println("=== 处理高价产品 ===");
        
        try (Stream<Product> productStream = productRepository.streamByMinPrice(minPrice)) {
            productStream
                .filter(product -> product.getStockQuantity() > 0)
                .sorted((p1, p2) -> p2.getPrice().compareTo(p1.getPrice()))
                .limit(10)
                .forEach(product -> {
                    System.out.printf("处理产品: %s, 价格: %s, 库存: %d%n", 
                                    product.getName(), product.getPrice(), product.getStockQuantity());
                });
        }
    }
    
    // 使用自定义迭代器处理产品
    public void processProductsByCategory(String category) {
        System.out.println("\n=== 处理" + category + "类别的产品 ===");
        
        Iterator<Product> iterator = productIterator.byCategory(category);
        int count = 0;
        while (iterator.hasNext() && count < 5) {
            Product product = iterator.next();
            System.out.println(product);
            count++;
        }
    }
    
    // 批量更新产品价格
    @Transactional
    public int updateProductPrices(String category, BigDecimal discountRate) {
        List<Product> products = productRepository.findByCategory(category);
        int updatedCount = 0;
        
        for (Product product : products) {
            BigDecimal originalPrice = product.getPrice();
            BigDecimal newPrice = originalPrice.multiply(BigDecimal.ONE.subtract(discountRate));
            product.setPrice(newPrice.setScale(2, RoundingMode.HALF_UP));
            productRepository.save(product);
            updatedCount++;
            
            System.out.printf("更新产品: %s, 原价: %s, 新价: %s%n", 
                            product.getName(), originalPrice, product.getPrice());
        }
        
        return updatedCount;
    }
    
    // 查找低库存产品
    public List<Product> findLowStockProducts(int threshold) {
        return productRepository.findLowStockProducts(threshold);
    }
}

// 客户端使用 - Client Usage
@SpringBootApplication
public class SpringDataJpaIteratorDemo {
    
    public static void main(String[] args) {
        SpringApplication.run(SpringDataJpaIteratorDemo.class, args);
        
        System.out.println("=== Spring Data JPA迭代器模式演示 ===");
        System.out.println("启动Spring Boot应用,测试JPA迭代器功能");
    }
    
    @Component
    public static class ProductDemoRunner implements CommandLineRunner {
        
        @Autowired
        private ProductService productService;
        
        @Autowired
        private ProductRepository productRepository;
        
        @Override
        public void run(String... args) throws Exception {
            System.out.println("\n--- 开始Spring Data JPA迭代器模式演示 ---");
            
            // 初始化测试数据
            initializeTestData();
            
            // 演示Stream API的使用
            productService.processExpensiveProducts(new BigDecimal("70.00"));
            
            // 演示自定义迭代器
            productService.processProductsByCategory("图书");
            
            // 演示批量更新
            System.out.println("\n--- 批量更新电子产品价格 ---");
            int updatedCount = productService.updateProductPrices("电子产品", new BigDecimal("0.1")); // 10%折扣
            System.out.println("更新了 " + updatedCount + " 个产品的价格");
            
            // 演示低库存查询
            System.out.println("\n--- 低库存产品 ---");
            List<Product> lowStockProducts = productService.findLowStockProducts(10);
            lowStockProducts.forEach(System.out::println);
            
            System.out.println("\n迭代器模式演示完成");
        }
        
        private void initializeTestData() {
            // 清空现有数据
            productRepository.deleteAll();
            
            // 添加测试数据
            List<Product> products = Arrays.asList(
                new Product("Java编程思想", new BigDecimal("108.00"), "图书", 20),
                new Product("Python基础教程", new BigDecimal("89.00"), "图书", 15),
                new Product("JavaScript高级程序设计", new BigDecimal("99.00"), "图书", 25),
                new Product("iPhone 13", new BigDecimal("5999.00"), "电子产品", 5),
                new Product("MacBook Pro", new BigDecimal("12999.00"), "电子产品", 3),
                new Product("AirPods Pro", new BigDecimal("1999.00"), "电子产品", 8),
                new Product("Spring实战", new BigDecimal("79.00"), "图书", 12),
                new Product("MyBatis技术内幕", new BigDecimal("85.00"), "图书", 18),
                new Product("Netty权威指南", new BigDecimal("118.00"), "图书", 7)
            );
            
            productRepository.saveAll(products);
            System.out.println("初始化测试数据完成,共添加了 " + products.size() + " 个产品");
        }
    }
}

迭代器模式与其他模式比较 (Comparison with Other Patterns)

特性迭代器模式组合模式访问者模式策略模式
目的顺序访问元素树形结构处理操作扩展算法选择
关注点遍历机制层次结构操作分离算法变化
使用场景集合遍历树形结构对象结构操作算法替换
结构特点迭代器接口递归组合双重分派策略接口
扩展性遍历方式扩展结构扩展操作扩展算法扩展

最佳实践 (Best Practices)

1. 迭代器设计 (Iterator Design)

  • 保持迭代器的轻量级和高效性
  • 确保迭代器的一致性(快速失败或安全失败)
  • 考虑并发环境下的线程安全问题

2. 聚合设计 (Aggregate Design)

  • 明确定义聚合的遍历语义
  • 支持多种迭代器实现
  • 考虑聚合的修改对迭代器的影响

3. 性能优化 (Performance Optimization)

  • 避免在迭代过程中频繁创建对象
  • 考虑使用延迟加载策略
  • 合理使用缓存机制

4. 错误处理 (Error Handling)

  • 提供清晰的异常处理机制
  • 在迭代器失效时给出明确的错误信息
  • 考虑边界情况的处理

5. 扩展性设计 (Extensibility Design)

  • 支持自定义迭代器实现
  • 考虑使用泛型提高类型安全性
  • 提供灵活的过滤和转换机制

优缺点 (Pros and Cons)

优点 (Advantages)

  1. 统一遍历接口:为不同的聚合结构提供统一的遍历接口
  2. 隐藏内部表示:客户端无需了解聚合对象的内部结构
  3. 支持多种遍历:可以为同一聚合提供多种遍历方式
  4. 简化聚合类:将遍历逻辑从聚合类中分离出来
  5. 支持并发遍历:多个迭代器可以同时进行遍历
  6. 提高代码复用性:迭代器可以在不同的聚合间共享

缺点 (Disadvantages)

  1. 增加复杂性:对于简单的聚合,使用迭代器模式可能过于复杂
  2. 性能开销:额外的迭代器对象会带来内存和性能开销
  3. 同步问题:在并发环境下需要处理同步问题
  4. 状态管理复杂:需要仔细管理迭代器的状态
  5. 不适合所有场景:对于某些特殊的遍历需求可能不够灵活

实际应用建议 (Practical Application Tips)

1. 遍历策略选择

  • 根据聚合的特性选择合适的遍历策略
  • 考虑使用懒惰求值来提高性能
  • 对于大数据集,考虑使用分页或流式处理

2. 并发处理

  • 在并发环境下使用线程安全的迭代器
  • 考虑使用不可变聚合来避免同步问题
  • 合理使用读写锁来提高并发性能

3. 内存管理

  • 及时释放不再使用的迭代器
  • 考虑使用弱引用来避免内存泄漏
  • 对于大数据集,使用流式处理减少内存占用

4. 测试策略

  • 测试迭代器的各种遍历场景
  • 测试在遍历过程中修改聚合的行为
  • 测试边界条件和异常情况

总结 (Summary)

迭代器模式是一种基础且重要的行为型设计模式,它通过提供统一的遍历接口,使得客户端可以透明地访问聚合对象的元素,而无需了解其内部结构。这种模式在现代编程语言中得到了广泛的应用,如Java的Collections Framework、C++的STL等。

在实际应用中,迭代器模式特别适合以下场景:

  • 需要遍历复杂的数据结构
  • 需要为同一聚合提供多种遍历方式
  • 需要隐藏聚合的内部表示
  • 需要支持多个同时进行的遍历

通过合理使用迭代器模式,可以构建出灵活、可扩展的系统架构,提高代码的可维护性和可扩展性。然而,需要注意避免过度设计,对于简单的聚合结构,直接使用语言内置的迭代机制可能更加合适。

22、嵌入式软件随机延迟生成与加密算法防护技术 本文探讨了嵌入式软件中的随机延迟生成方法与块密码软件实现的高阶掩码及洗牌技术。重点介绍了浮动均值延迟生成方法,其在8位AVR平台上的实现效率为Θ(1),显著提升了抗相关功率分析(CPA)攻击的能力,相比传统方法更安全且轻量。同时,分析了高阶掩码与洗牌技术结合的方案,通过理论建模量化其对高级差分功率分析(DPA)攻击的抵抗能力,并以AES为例展示了该方案的应用流程。最后对比了不同防护技术在安全性与开销之间的权衡,为实际应用中选择合适的安全策略提供了依据。未来可进一步优化实现效率并融合多种防护手段以应对复杂安全 阅读详情

相关推荐

NOAA气象数据下载攻略

各方搜寻气象数据下载途径,发现网上最多的就是从NOAA下载,但是中途有尝试过很多次都没有下载到,每次都是显示不可用,今天终于下载成功了,特此记录。 首先我是从这个网址进入的:National Centers for Environmental Information (NCEI) formerly known as National Climatic Data Center (NCDC) | NCEI offers access to the most significant archives of oc

lianqian66的博客 3万+

设计模式14 - 迭代器模式【Iterator Pattern】

迭代器模式 已经过时了,随便看看吧,下面的代码都是复制过来的。 定义: 提供一种方法顺序访问一个聚合对象中的各种元素,而又不暴露该对象的内部表示。 举例: 未修改前的代码: public interface IProject { //从老板这里看到的就是项目信息 public String getProjectInfo(); } public cla...

阿甘兄 709

ESP32C6+ESP-IDF5.2实战:基于RS485的ModbusRTU从站开发与调试

本文详细介绍了基于ESP32C6和ESP-IDF5.2开发ModbusRTU从站的实战指南。涵盖硬件连接、协议实现、ESP-Modbus库移植、寄存器映射及调试技巧,帮助开发者快速构建稳定可靠的工业级RS485通信节点,并解决常见通信故障。

play7的博客 1188

DesignPattern_迭代器模式_14

文章目录迭代器模式定义代码实现基础代码迭代器模式 迭代器模式 学习自 《设计模式之禅(第二版)》 定义 Provide a way to access the elements of an aggregate object sequentially without exposing itsunderlying representation. 它提供一种方法访问一个容器对象中各个元素,而又不需暴露该对象的内部细节。 迭代器是为容器服务的,那什么是容器呢?能容纳对象的所有类型都可以称之为容器,例如Collect

qq_38438909的博客 135

别再手动拷贝文件了!用Keil MDK的Pack Installer一键搞定STM32上的RT-Thread Nano移植

本文详细介绍了如何使用Keil MDK的Pack Installer一键快速移植RT-Thread Nano到STM32项目,告别繁琐的手动拷贝和配置过程。通过自动化版本管理和依赖处理,移植时间从47分钟缩短至3分钟,大幅提升开发效率。文章还提供了实战步骤、高级配置技巧和常见问题解决方案,帮助开发者轻松实现RTOS集成。

weixin_29194817的博客 364

移动通信基础(13)TDL、CDL、信道相关性

参考《U型槽无线信道多径传播特性测量与建模方法的研究》、《5G信号源中的信道模拟与仿真研究》衰落衰落理解为信号幅度在时间和频率上的不断波动,是无线信道一个重要的恶化特性。信道幅度恶化的两个主要来源分别是加性噪声和信号衰落,高斯白噪声信道模型就是典型的加性噪声,信号衰落引起的是乘性的信号扰动,与加性噪声从原理上完全不同。信道的频率选择性衰落组为无线信道的重要特征之一,是人们进行无线系统设计考虑的重要因素,决定了导频隔间的大小。...

tybAly的博客 2万+

C#设计模式(16)——迭代器模式(Iterator Pattern)

C#设计模式(16)——迭代器模式(Iterator Pattern) 一、引言   在上篇博文中分享了我对命令模式的理解,命令模式主要是把行为进行抽象成命令,使得请求者的行为和接受者的行为形成低耦合。在一章中,将介绍一下迭代器模式。下面废话不多说了,直接进入本博文的主题。 二、迭代器模式的介绍   迭代器是针对集合对象而生的,对于集合对象而...

fgmah2000的博客 182

AUTOSAR/汽车行业

AUTOSAR架构及汽车产业链相关介绍

m0_54254513的博客 1万+

Iterator Pattern(迭代器模式)

对迭代器模式的学习、理解和应用案例

我与岁月的森林的博客 260

TP4054充电电路发热严重?手把手教你调整电阻值降低温度(附实测数据)

本文针对TP4054锂电池充电电路发热严重的问题,提供了详细的排错与解决方案。通过分析发热原理,指出核心在于PROG引脚电阻值设定,并手把手指导如何计算和选择正确的电阻以降低充电电流与温度。文末附有不同电阻下的实测温度与性能数据,为电子爱好者和工程师提供了实用的调试参考。

p4q5r6s7t的博客 406

久坐不慌,健康护航 —— 智能震动提醒坐垫的设计与实现

硬件核心:选用 ESP32 为主控,HX711 + 应变片实现精准压力检测,8050 三极管驱动震动马达,锂电池 + TP4056 满足便携供电需求;软件逻辑:核心是 “压力阈值判断 + 时间计时”,达到久坐阈值后触发震动提醒,流程图清晰体现了循环检测、状态重置的核心逻辑;代码特性:代码注释完善,阈值可灵活调整,支持串口调试,新手可直接编译烧录并根据实际场景校准。

weixin_42300449的博客 401

行为类型11-3:迭代器模式(Iterator Pattern)

1. 概述 迭代器模式(Iterator Pattern)是 Java 和 .Net 编程环境中非常常用的设计模式。这种模式用于顺序访问集合对象的元素,不需要知道集合对象的底层表示。 给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。 2. 介绍 2.1 意图 提供一种方法顺序访问一个聚合对象中各个元素, 而又无须暴露该对象的内部表示。 2.2 主要解...

王道长的技术博客 260

Isaac Lab 强化学习全身控制策略 Sim2Real 宇树人形机器人训练部署 HOVER

《IsaacLab策略训练与部署指南》提供了在仿真和真实机器人上实现HOVER全身控制策略的完整流程。主要内容包括:1) Linux环境下的IsaacLab安装与HOVER资源库配置;2) 使用1024个并行环境训练教师/学生策略的详细步骤;3) 策略测试与评估方法;4) Sim2Sim仿真验证和Sim2Real真实机器人部署方案。本教程特别针对Unitree H1仿人机器人,包含运动数据准备、策略训练、性能评估到硬件部署的全链条实现方案,为机器人控制策略开发提供标准化参考框架。

机器人控制与仿真应用 3070

迭代器模式简析

目的:提供一种方法顺序访问聚合对象中的元素,而不暴露其内部表示解决问题:以不同方式遍历聚合对象原理:聚合类中保留聚合对象存储内部数据的职责,而降遍历内部数据的职责交给迭代器来完成,以实现“单一职责”的原则UML类图:                ...

封访梦的博客 4177

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

33迭代器模式(Iterator Pattern)

动机(Motivate): 在软件构建过程中,集合对象内部结构常常变化各异。但对于这些集合对象,我们希望在不暴露其内部结构的同时,可以让外部客户代码透明地访问其中包含的元素;同时这种“透明遍历”也为“ 同一种算法在多种集合对象上进行操作”提供了可能。 使用面向对象技术将这种遍历机制抽象为“迭代器对象”为“应对变化中的集合对象”提供了一种优雅的方法。意图(Intent): 提...

sinolover的专栏 555

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

第 14 章 迭代器模式【Iterator Pattern】

以下内容出自:&lt;&lt;24种设计模式介绍与6大设计原则&gt;&gt;     周五下午,我正在看技术网站,第六感官发觉有人在身后,扭头一看,我C,老大站在背后,赶忙站起来,   “王经理,你找我?” 我说。  “哦,在看技术呀。有个事情找你谈一下,你到我办公室来一下。” 老大说。  到老大办公室,  “是这样,刚刚我在看季报,我们每个项目的支出费用都很高,项目情况复杂,人员情况也不...

weixin_33937499的博客 102

C#设计模式——迭代器模式(Iterator Pattern)

一、概述在软件开发过程中,我们可能会希望在不暴露一个集合对象内部结构的同时,可以让外部代码透明地访问其中包含的元素。迭代器模式可以解决这一问题。二、迭代器模式迭代器模式提供一种方法顺序访问一个集合对象中的各个元素,而又不需暴露该对象的内部表示。迭代器模式的结构图如下: Iterator定义了访问和遍历元素的接口。ConcreteIterator表示具体的迭代器,它实现了Iterator接...

weixin_33834679的博客 106

设计模式-迭代器模式(Iterator Pattern)

本文由@呆代待殆原创,转载请注明出处:http://www.cnblogs.com/coffeeSS/ 迭代器模式简介 迭代器相信大部分人都不陌生,java/c++等很多编程语言的容器类都支持迭代器操作,这个模式就是介绍迭代器实现的细节。 迭代器模式的定义和基本结构 定义:提供一个可以顺序访问一个聚合对象中的各个元素有不暴露器内部实现的方法。 一张来自《Head First》...

weixin_30951389的博客 87

设计模式(16)——迭代器模式(Iterator Pattern)

一、引言 在上篇博文中分享了我对命令模式的理解,命令模式主要是把行为进行抽象成命令,使得请求者的行为和接受者的行为形成低耦合。在一章中,将介绍一下迭代器模式。下面废话不多说了,直接进入本博文的主题。 二、迭代器模式的介绍 迭代器是针对集合对象而生的,对于集合对象而言,必然涉及到集合元素的添加删除操作,同时也肯定支持遍历集合元素的操作,我们此时可以把遍历操作也放在集合对象中,但这样的话,集合对

Foreach 392

C#设计模式之十五迭代器模式(Iterator Pattern)【行为型】

C#设计模式之十五迭代器模式(Iterator Pattern)【行为型】 原文:C#设计模式之十五迭代器模式(Iterator Pattern)【行为型】一、引言 今天我们开始讲“行为型”设计模式的第三个模式,该模式是【迭代器模式】,英文名称是:Iterator Pattern。还是老套路,先从名字上来看看。“迭代器模式”我第一次看到这个...

weixin_30713953的博客 79

解读设计模式----迭代器模式(Iterator Pattern)

一、你在开发中使用过迭代吗?      当你在使用JavaScript开发客户端应用的时候使用过for...in吗?    1&lt;script type="text/javascript"&gt;  2var obj;  3useForIn = function ()  4{  5   obj = (0,1,2,3,4,5,6,7,8,9);  6   for(var o in...

weixin_34341117的博客 77

AI短剧《一善坊》技术解析:多模态AIGC整合与自动化生产流水线构建

多模态AI生成内容(AIGC)技术正推动视频内容创作进入新阶段,其核心原理在于整合文本、图像、语音等多种生成模型,构建端到端的自动化生产管线。从技术价值看,这不仅能大幅提升内容产出效率,也为个性化、规模化叙事提供了可能。在应用场景上,AI视频生成、数字人驱动、语音合成等技术正被集成于短视频、短剧、虚拟主播等领域。本文以《一善坊》AI短剧为例,深入探讨如何将Stable Diffusion、TTS、数字人驱动等分散的AIGC能力串联,构建一套支持批量任务与长视频渲染的自动化流水线,为开发者提供从技术选型、环境

weixin_34013044的博客 341
上一篇: 设计模式-13命令模式Command Pattern
下一篇: 设计模式-15中介者模式Mediator Pattern
d3y1
博客等级 码龄12年 1438粉丝 2787原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值