设计模式之一(Iterator模式)


表 1-1 类和接口的一览表

名字说明
Aggregate表示集合的接口
Iterator遍历集合的接口
Book表示书的类
BookShelf表示书架的类
BookShelfIterator遍历书架的类
Main测试程序行为的类
/**
* Aggregate接口
*/
public interface Aggregate{
    Iterator iterator;
}
/**
* Iterator接口
*/
public interface Iterator{
    boolean hasNext();
    Object next();
}
/**
* Book类
*/
public class Book {
   private String name;
   
   public Book(){}
   
   public Book(String name) {
        this.name = name;
   }
   
   public String getName() {
        return this.name;
   }
}
/**
* BookShelf类
*/
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;
    }
    
	public Iterator iterator() {
        return new BookShelfIterator(this);
    }
}
/**
* BookShelfIterator类
*/
public class BookShelfIterator implements Iterator {
    private BookShelf bookShelf;
    private int index;
    public BookShelfIterator (BookShelf bookShelf) {
        this.bookShelf = bookShelf;
        this.index = 0;
    }
    
    public boolean hasNext() {
        if(index < bookShelf.getLength())
            return true;
        else
            return false;
    }
    
    public Object next(){
        Book book = bookShelf.getBookAt(index);
        index++;
        return book;
    }
}
/**
* Main类
*/
public class Main{
   public static void main(String[] agrs){
        BookShelf bookShelf = new BookShelf(2);
        bookShelf.appendBook(new Book("111"));
        bookShelf.appendBook(new Book("222"));
        Iterator iterator = bookShelf.iterator();
        while(iterator.hasNext()){
            Book book = (Book)iterator.next();
            System.out.println(book.getName());
        }
   }
}

 为什么要引入Ierator这种设计模式?因为引入了Iterator后可以将遍历与实现分离开来。看遍历的代码:

while(iterator.hasNext()){
    Book book = (Book)iterator.next();
    System.out.println(book.getName());
}

 这里只使用了Iterator的hasNext方法和next方法,并没有调用BookShelf方法。也就是说,这里的while循环不依赖于BookShelf的实现。
 如果编写BookShelf的开发人员决定放弃用数组来管理文本,而是用其他的容器类,那么只需要BookShelf的iterator方法能正确地返回Iterator实例,我们不需要更改在业务中的while循环迭代遍历的代码,代码都可以正常工作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值