图解设计模式-Iterator模式

使用抽象类和接口,弱化类之间的耦合,使类可以更容易组件化
不使用具体类编程,要优先使用抽象类和接口编程
 
角色划分:
Iterator迭代器接口,定义遍历元素的接口,hasNext判断是否有下一个、next获得下一个值
ConcreteIterator:迭代器具体的实现类,实现了hasNext、next两个方法,需要根据具体的被迭代对象进行自定。
Aggregate集合接口,包含了获得Iterator迭代器的方法
ConcreteAggregate集合的具体实现类,实现了了获得Iterator迭代器的方法
  • 定义被编列的类
public class Book {

    private String name;

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

    public String getName() {
        return name;
    }
}
定义遍历接口
public interface Iterator {
    public abstract boolean hasNext();
    public abstract Object next();
}

定义书架类集合

import java.util.ArrayList;
import java.util.List;

public class BookShelf extends Aggregate {

    private List<Book> bookList = new ArrayList<>();

    public void addBook(Book book) {
        bookList.add(book);
    }

    public Book getIndex(int i) {
        return bookList.get(i);
    }

    public int getLength() {
        return bookList.size();
    }

    @Override
    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;
    }
    @Override
    public boolean hasNext() {
        if(bookShelf.getLength()>index) {
            return true;
        }
        return false;
    }

    @Override
    public Object next() {
        Book book = bookShelf.getIndex(index);
        index++;
        return book;
    }
}

定义测试类

public class Main {
    public static void main(String[] args){
        BookShelf bookShelf = new BookShelf();
        bookShelf.addBook(new Book("数学"));
        bookShelf.addBook(new Book("物理"));
        bookShelf.addBook(new Book("化学"));
        Iterator iterator = bookShelf.iterator();
        for(;iterator.hasNext();) {
            Book book = (Book)iterator.next();
            System.out.println(book.getName());
        }
    }
}

总结:被遍历的集合类(BookShelf)与遍历类(BookShelfIterator)分开定义,进行解耦,方便扩展。

posted @ 2018-08-27 23:31  使用D  阅读(197)  评论(0编辑  收藏  举报