设计模式 - 迭代器模式 - Itreator
概念
它提供一种方法访问一个容器对象中的各个元素,而不需要暴露该对象的内部细节
概念说明
- 迭代器是为容器服务的,那么什么是容器?能够容纳对象的所有类型(Collection集合类型、Set类型等)
- 迭代器模式就是为了解决便利这些容器中元素而诞生的
UML
![](https://img.haomeiwen.com/i14179336/51f846ce79a5ec0d.png)
-
Itreator(迭代器角色):负责定义访问和遍历元素的接口;JDK已定义
-
ConcreteIterator(具体迭代器角色):实现迭代器接口,完成容器元素遍历;
迭代器中删除元素:1.删除当前元素;2.当前游标指向下一个元素
-
Iterable(获取迭代器角色):返回一个迭代器,实现该接口允许对象称为ForEarch语句的目标
(就可以通过forEarch语句遍历容器)
-
ConcreateIterable(具体获取迭代器角色):一般容器类实现Iterable(如AbstractList)
例子
迭代器实现
public class ArrayIterator implements Iterator<String> {
private BookArray bookArray;
private int index;
public ArrayIterator(BookArray bookArray) {
this.bookArray = bookArray;
}
@Override
public boolean hasNext() {
if (index < bookArray.size()) {
return true;
} else {
return false;
}
}
@Override
public String next() {
return bookArray.getBook(index++);
}
@Override
public void remove() {
// TODO Auto-generated method stub
}
}
容器实现
public class BookArray implements Iterable<String>{
private String[] books;
private int index;
public BookArray(int arraySize) {
books = new String[arraySize];
}
@Override
public Iterator<String> iterator() {
return new ArrayIterator(this);
}
public void addBook(String book) {
if (index > books.length)
throw new RuntimeException("index out of array size!");
this.books[index++] = book;
}
public String getBook(int index) {
if (index > books.length - 1)
throw new RuntimeException("index out of array size!");
return books[index];
}
public int size() {
return books.length;
}
}
测试类
public static void main(String[] args) {
BookArray bookArray = new BookArray(4);
bookArray.addBook("java编程思想");
bookArray.addBook("java核心技术");
bookArray.addBook("设计模式之禅");
bookArray.addBook("Spring实战");
Iterator<String> iterator = bookArray.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
输出
java编程思想
java核心技术
设计模式之禅
Spring实战
网友评论