图解设计模式读书笔记(一)——Iterator模式

一、涉及的类

public interface Aggregate {
    public abstract Iterator iterator();
}
public interface Iterator {
    public abstract boolean hasNext();
    public abstract Object next();
}
public class Book {
    private String name;
    public Book(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
}
import java.util.ArrayList;

public class BookShelf implements Aggregate {
    private ArrayList books;   
    public BookShelf(int initialsize) {         
        this.books = new ArrayList(initialsize);   
    }                                           
    public Book getBookAt(int index) {
        return (Book)books.get(index);          
    }
    public void appendBook(Book book) {
        books.add(book);                        
    }
    public int getLength() {
        return books.size();                    
    }
    public Iterator iterator() {
        return new BookShelfIterator(this);
    }
}
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;
    }
}

 

二、可解决场景

       有个BookShelf对象,代表一个书架,其维护了一个集合/数组,实现对Book的管理,当外部使用BookShelf对象的时候,如果需要遍历书架中的Book对象,普通实现是获取BookShelf里的集合类/数组,然后通过for或者while去循环。这种情况下使用者是严重依赖于BookShelf的,因为如果BookShelf中的集合类一改变,则调用者也需要跟者修改代码,这不便于组件化,另外,如果由于数据结构的变化,需要修改遍历方法,则使用者也需要去实现遍历算法,这对使用者来说太不方便了。

 

三、基本思想

 

        BookShelf实现Aggregate接口,该接口的作用是生成Iterator对象。BookShelfIterator就是实现Iterator接口的Iterator对象。BookShelf里的iterator()方法这返回BookShelfIterator。这样就就把遍历的操作全封装在BookShelfIterator中,BookShelf的使用者只需要通过该方法拿到BookShelfIterator对象,则可通过Iterator接口的方法对BookShelf的集合进行遍历,而不需要去关系BookShelf对象中的集合是哪种集合,也不需要关系遍历的算法是哪种算法。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值