designpatterns -- iterator

本文介绍了一种使用Java实现的迭代器模式,通过BookShelf类作为聚合类,BookShelfIterator类作为具体迭代器,实现了对书籍集合的遍历。该模式分离了遍历行为与聚合对象,使得增加新的遍历方式更为灵活。

迭代器模式 出处 图解设计模式 结城浩著

iterator



/**
 * @author linx
 * @version 1.0
 * @created 19-十二月-2017 13:08:57
 */
public interface Iterator {

	public abstract boolean hasNext();

	public  abstract Object next();

}


/**
 * @author linx
 * @version 1.0
 * @created 19-十二月-2017 13:08:56
 */
public class BookShelfIterator implements Iterator {

	private BookShelf bookShelf_;
	private int index;
	public BookShelfIterator(BookShelf bookShelf){
		this.bookShelf_ = bookShelf;
		this.index = 0;
	}

	public void finalize() throws Throwable {

	}

	public boolean hasNext(){
		if (index < bookShelf_.getLength()) {
			return true;
		} else {
			return false;
		}
	}

	public Object next(){
		Book book = bookShelf_.getBookAt(index);
		index++;
		return book;
	}

}


/**
 * @author linx
 * @version 1.0
 * @created 19-十二月-2017 13:08:53
 */
public interface Aggregate {

	public abstract Iterator iterator();

}


/**
 * @author linx
 * @version 1.0
 * @created 19-十二月-2017 13:08:55
 */
public class BookShelf implements Aggregate {

	private Book[] books;
	private int last = 0;
	
	public BookShelf(int maxsize){
		this.books = new Book[maxsize];
	}

	public void finalize() throws Throwable {

	}

	public void appendBook(Book book){
		this.books[last] = book;
		last++;
	}

	public Book getBookAt(int index){
		return books[index];
	}

	public int getLength(){
		return last;
	}

	public Iterator iterator() {
		return new BookShelfIterator(this);
	}

}


/**
 * @author linx
 * @version 1.0
 * @created 19-十二月-2017 13:08:55
 */
public class Book {
	private String name;


	public Book(String name) {
		this.name = name;
	}

	public String getName() {
		return this.name;
	}

	public void finalize() throws Throwable {

	}

}


/**
 * @author linx
 * @version 1.0
 * @created 19-十二月-2017 13:08:55
 */

/* The test class or client */
class Test {
    public static void main(String[] args) {
        BookShelf bookShelf = new BookShelf(4);
        bookShelf.appendBook(new Book("A"));
        bookShelf.appendBook(new Book("B"));
        bookShelf.appendBook(new Book("C"));
        bookShelf.appendBook(new Book("D"));
        Iterator it = bookShelf.iterator();
        while(it.hasNext()) {
            Book book = (Book)it.next();
            System.out.println(book.getName());
        }
    }
}

转载于:https://my.oschina.net/randy1986/blog/1592171

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值