图解设计模式Iterator模式

作者: MWY | 来源:发表于2017-01-10 23:04 被阅读144次

    Iterator设计模式UML图

    Paste_Image.png

    Iterator(迭代器)

    //负责定义按顺序遍历各个元素的接口
    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设计模式的优点

    • 将遍历和实现分开

    相关文章

      网友评论

        本文标题:图解设计模式Iterator模式

        本文链接:https://www.haomeiwen.com/subject/urulbttx.html