設計模式(一):Iterator模式(迭代器模式)
阿新 • • 發佈:2019-01-03
Iterator模式(迭代器模式)
迭代器模式
需求
一個實體類Book,一個Book的集合類 BookList,BookList提供遍歷方法。
實現
Book類
public class Book {
private String name;
public Book(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
BookList類
public class BookList {
private Book[] books;
private int last = 0;
private int index = 0;
public BookList(int maxsize) {
this.books = new Book[maxsize];
}
public void appendBook(Book book) {
this.books[last] = book;
last++;
}
// 返回是否還有下一個元素
public boolean hasNext () {
return index < last;
}
// 返回當前元素,指標指向下一個元素
public Book next() {
Book book = books[index];
index++;
return book;
}
}
測試類:
@Test
public void test() {
BookList bl = new BookList(4);
bl.appendBook(new Book("a"));
bl.appendBook(new Book("b"));
bl.appendBook(new Book("c"));
bl. appendBook(new Book("d"));
while (bl.hasNext()) {
Book book = bl.next();
System.out.println(book.getName());
}
}
上面可以完成遍歷,但是耦合度太高,應採用面向介面程式設計的思想編碼。
修改後
Book.java實體類:
public class Book {
private String name;
public Book(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
Aggregate.java集合類介面,提供iterator方法定義:
public interface Aggregate {
Iterator iterator();
}
Iterator介面,提供next和hasNext方法的定義:
/**
* Iterator介面類
*/
public interface Iterator {
// 返回當前元素,指標指向下一個元素,Object返回型別更具有通用性
Object next();
// 是否有下一個元素
boolean hasNext();
}
BookList.java 作為Book類的集合,實現Aggregate介面:
// Book類集合
public class BookList implements Aggregate {
// 用陣列儲存元素
private Book[] books;
// 要新新增元素的索引,也是這個集合的長度
private int last = 0;
// 初始化陣列長度
public BookList(int maxsize) {
this.books = new Book[maxsize];
}
// 向集合BookList中新增元素(也就是向books這個陣列中新增元素)
public void appendBook(Book book) {
this.books[last] = book;
// 新增一個元素,長度加一
last++;
}
// 獲取集合的長度
public int getLength() {
// 長度,不是索引
return last;
}
// 獲取指定索引的元素
public Book getEleAt(int index) {
return this.books[index];
}
// 返回一個迭代器
@Override
public Iterator iterator() {
return new BookListIterator(this);
}
}
BookListIterator作為BookList迭代器的具體實現:
// BookList集合的迭代器
public class BookListIterator implements Iterator {
private BookList bookList;
private int index = 0;
public BookListIterator(BookList bookList) {
this.bookList = bookList;
}
// 返回當前元素
@Override
public Object next() {
Book book = bookList.getEleAt(index);
index++;
return book;
}
@Override
public boolean hasNext() {
// 當前比例的索引Index小於集合長度就有下一個元素
return index < this.bookList.getLength();
}
}
測試:
@Test
public void mainTest() {
BookList bookList = new BookList(4);
bookList.appendBook(new Book("d"));
bookList.appendBook(new Book("c"));
bookList.appendBook(new Book("b"));
bookList.appendBook(new Book("A"));
Iterator iterator = bookList.iterator();
while (iterator.hasNext()) {
Book book = (Book)iterator.next();
System.out.println(book.getName());
}
}