大家应该都用过java的Iterator。比如说:
List list=new ArrayList();
list.add("1");
list.add("2");
list.add("3");
Iterator iter=list.iterator();
while(iter.hasNext()) {
String s=(String)iter.next();
System.out.println(s);
}
那么现在就来看一下iterator模式。
把书籍(book)放到书架(BookShelf)上,并用迭代器输出。代码如下:
//Aggregate.java
package com.cool;
public interface Aggregate {
public Iterator iterator();
}
//Iterator.java
package com.cool;
public interface Iterator {
public boolean hasNext();
public Object next();
}
//Book.java
package com.cool;
/**
* 书类
* @author cool
*
*/
public class Book {
private String name;
public Book(String name) {
this.name=name;
}
public String getName() {
return name;
}
}
//BookShelf.java
package com.cool;
/**
* 书架<br>
* 用来放书
* @author cool
*
*/
public class BookShelf implements Aggregate {
private Book[] book;
private int last;
private int maxnum;
/**
*
* @param maxnum 最多能放几本书
*/
public BookShelf(int maxnum) {
last=0;
this.maxnum=maxnum;
book=new Book[maxnum];
}
/**
* 取得书
* @param index
* @return
*/
public Book getBookAt(int index) {
if(index>=0 && index<last) {
return book[index];
} else {
return book[0];
}
}
/**
* 增加书
* @param book
* @return
*/
public boolean appendBook(Book book) {
if(last<maxnum) {
this.book[last]=book;
++last;
return true;
} else {
return false;
}
}
public int getLength() {
return last;
}
/**
* 取得迭代器
*/
public Iterator iterator() {
return new BookShelfIterator(this);
}
}
//BookShelfIterator.java
package com.cool;
public class BookShelfIterator implements Iterator {
private BookShelf bookShelf;
private int index;
public BookShelfIterator(BookShelf bookShelf) {
this.bookShelf=bookShelf;
index=0;
}
public boolean hasNext() {
if(index<bookShelf.getLength()) {
return true;
} else {
return false;
}
}
public Object next() {
if(hasNext()) {
Book book=bookShelf.getBookAt(index);
++index;
return book;
} else {
return null;
}
}
}
//Test.java
package com.cool;
/**
* 测试类
* @author cool
*
*/
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BookShelf bookShelf=new BookShelf(4);
bookShelf.appendBook(new Book("1"));
bookShelf.appendBook(new Book("2"));
bookShelf.appendBook(new Book("3"));
bookShelf.appendBook(new Book("4"));
if(bookShelf.getLength()==4) {
print("getLength pass");
}
Iterator iter=bookShelf.iterator();
while(iter.hasNext()) {
Book book=(Book)iter.next();
print(book.getName());
}
}
private static void print(Object o) {
System.out.println(o);
}
}