图解设计模式Iterator模式
2017-01-10 本文已影响144人
MWY
Iterator设计模式UML图
Paste_Image.pngIterator(迭代器)
//负责定义按顺序遍历各个元素的接口
package me.maweiyi;
/**
* Created by MWY
* Date: 1/10/17
* Time: 22:10
*/
public interface Iterator {
public abstract boolean hasNext();
public abstract Object next();
}
ConcreteIterator(具体的迭代器)
//负责实现具体的迭代器
package me.maweiyi;
/**
* Created by MWY
* Date: 1/10/17
* Time: 22:21
*/
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 false;
if (index < bookShelf.getLength()) {
return true;
} else {
return false;
}
}
@Override
public Object next() {
//return null;
Book book = bookShelf.getBookAt(index);
index++;
return book;
}
}
Aggregate(集合)
//负责定义创建Iterator的接口
package me.maweiyi;
/**
* Created by MWY
* Date: 1/10/17
* Time: 22:09
*/
public interface Aggregate {
public abstract Iterator iterator();
}
ConcreteAggregate(具体的集合)
//实现Aggregate创建的接口,创建出具体的Iterator
package me.maweiyi;
/**
* Created by MWY
* Date: 1/10/17
* Time: 22:15
*/
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 null;
return new BookShelfIterator(this);
}
}
Iterator设计模式的优点
- 将遍历和实现分开