迭代器模式 (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)
实现方式 (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)
- 统一遍历接口:为不同的聚合结构提供统一的遍历接口
- 隐藏内部表示:客户端无需了解聚合对象的内部结构
- 支持多种遍历:可以为同一聚合提供多种遍历方式
- 简化聚合类:将遍历逻辑从聚合类中分离出来
- 支持并发遍历:多个迭代器可以同时进行遍历
- 提高代码复用性:迭代器可以在不同的聚合间共享
缺点 (Disadvantages)
- 增加复杂性:对于简单的聚合,使用迭代器模式可能过于复杂
- 性能开销:额外的迭代器对象会带来内存和性能开销
- 同步问题:在并发环境下需要处理同步问题
- 状态管理复杂:需要仔细管理迭代器的状态
- 不适合所有场景:对于某些特殊的遍历需求可能不够灵活
实际应用建议 (Practical Application Tips)
1. 遍历策略选择
- 根据聚合的特性选择合适的遍历策略
- 考虑使用懒惰求值来提高性能
- 对于大数据集,考虑使用分页或流式处理
2. 并发处理
- 在并发环境下使用线程安全的迭代器
- 考虑使用不可变聚合来避免同步问题
- 合理使用读写锁来提高并发性能
3. 内存管理
- 及时释放不再使用的迭代器
- 考虑使用弱引用来避免内存泄漏
- 对于大数据集,使用流式处理减少内存占用
4. 测试策略
- 测试迭代器的各种遍历场景
- 测试在遍历过程中修改聚合的行为
- 测试边界条件和异常情况
总结 (Summary)
迭代器模式是一种基础且重要的行为型设计模式,它通过提供统一的遍历接口,使得客户端可以透明地访问聚合对象的元素,而无需了解其内部结构。这种模式在现代编程语言中得到了广泛的应用,如Java的Collections Framework、C++的STL等。
在实际应用中,迭代器模式特别适合以下场景:
- 需要遍历复杂的数据结构
- 需要为同一聚合提供多种遍历方式
- 需要隐藏聚合的内部表示
- 需要支持多个同时进行的遍历
通过合理使用迭代器模式,可以构建出灵活、可扩展的系统架构,提高代码的可维护性和可扩展性。然而,需要注意避免过度设计,对于简单的聚合结构,直接使用语言内置的迭代机制可能更加合适。
3万+



被折叠的 条评论
为什么被折叠?



