本人所学设计模式皆出自于 结城浩先生的《图解设计模式》。
类图:
Iterator类图
示例代码类图
为什使用Iterator模式
如果编写BookShelf的开发人员决定放弃用数组来管理书本,而是使用Vector来管理,不管BookShelf如何变化,只要BookShelf的iterator方法能够返回Iterator的实例,那么对于程序的调用者来说,并不用担心调用方式会发生变化,不改变调用方法,一样可以使程序继续工作。
举例代码
package com.qiang.iterator;
/**
* 表示集合的接口
*
* @author zhangxinqiang
* @date 2018/2/10
*/
public interface Aggregate {
/**
* 创建遍历集合的接口
*
* @return 遍历集合的接口
*/
Iterator iterator();
}
package com.qiang.iterator;
/**
* 遍历集合的接口
*
* @author zhangxinqiang
* @date 2018/2/10
*/
public interface Iterator {
/**
* 是否还有下一个
*
* @return 是、否
*/
boolean hasNext();
/**
* 下一个遍历结果
*
* @return 下一个
*/
Object next();
}
package com.qiang;
import com.qiang.iterator.Aggregate;
import com.qiang.iterator.Iterator;
import com.qiang.model.Book;
/**
* 书架
*
* @author zhangxinqiang
* @date 2018/2/10
*/
public class BookShelf implements Aggregate {
private Book[] books;
private int last = 0;
public BookShelf(int maxSize) {
this.books = new Book[maxSize];
}
public Book getBookAt(int index) {
return books[index];
}
public void appendBook(Book book) {
this.books[last] = book;
last++;
}
public int getLength() {
return last;
}
@Override
public Iterator iterator() {
return new BookShelfIterator(this);
}
}
package com.qiang.model;
/**
* 书籍
*
* @author zhangxinqiang
* @date 2018/2/10
*/
public class Book {
private String name;
public Book(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.qiang;
import com.qiang.iterator.Iterator;
import com.qiang.model.Book;
/**
* 书架迭代遍历
*
* @author zhangxinqiang
* @date 2018/2/10
*/
public class BookShelfIterator implements Iterator {
private BookShelf bookShelf;
private int index;
public BookShelfIterator(BookShelf bookShelf) {
this.bookShelf = bookShelf;
this.index = 0;
}
@Override
public boolean hasNext() {
return index < bookShelf.getLength();
}
@Override
public Object next() {
Book book = bookShelf.getBookAt(index);
index++;
return book;
}
}
package com.qiang;
import com.qiang.iterator.Iterator;
import com.qiang.model.Book;
/**
* 测试方法
*
* @author zhangxinqiang
* @date 2018/2/10
*/
public class Test {
public static void main(String[] args) {
//能装5本书的书架
BookShelf bookShelf = new BookShelf(7);
//放4本书
bookShelf.appendBook(new Book("Think In Java"));
bookShelf.appendBook(new Book("Design Patterns"));
bookShelf.appendBook(new Book("Understanding the JVM"));
bookShelf.appendBook(new Book("Effective Java"));
Iterator iterator = bookShelf.iterator();
while (iterator.hasNext()) {
Book book = (Book) iterator.next();
System.out.println(book.getName());
}
}
}
由于书架中管理书籍的是数组,会造成书的数量超过指定书架容量,无法继续添加书籍,所以建议使用List集合来做容器。
注意:示例代码类图中接口方法我忘记标记为抽象了