码迷,mamicode.com
首页 > 其他好文 > 详细

迭代器模式

时间:2017-04-07 23:02:49      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:end   etl   []   over   span   img   als   gre   技术分享   

集合类中包含很多数据结构:数组、散列表、ArrayList等,这些集合类的迭代方法都不一样。为了隐藏迭代的具体实现 ,抽象集合类中引用抽象迭代器,具体的集合类引用具体的迭代类,在具体迭代类实现便利具体集合类的方法

技术分享

 

package iterator;

import java.util.Iterator;

/**
 * 抽象集合类,引用抽象迭代类
 */
public interface Aggregate {
    public abstract Iterator iterator();
}

 

package iterator;

/**
 * Created by marcopan on 17/4/7.
 */
public class Book {
    private String name;

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

 

package iterator;

import java.util.Iterator;

/**
 * 具体集合类
 */
public class BookShelf implements Aggregate {
    Book[] books;
    int index = 0;

    public BookShelf(int maxium) {
        books = new Book[maxium];
    }

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

    public void appendBook(Book newBook) {
        books[index++] = newBook;
    }

    public int getLength() {
        return index;
    }

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

 

package iterator;

import java.util.Iterator;

/**
 * 具体迭代类,Iterator是抽象迭代类
 */
public class BookShelfIterator implements Iterator {
    private BookShelf bookShelf;
    private int index = 0;

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

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

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

 

package iterator;

import java.util.Iterator;

/**
 * Created by marcopan on 17/4/7.
 */
public class IteratorTest {
    public static void main(String[] args) {
        BookShelf shelf = new BookShelf(4);
        shelf.appendBook(new Book("a"));
        shelf.appendBook(new Book("b"));
        shelf.appendBook(new Book("c"));
        shelf.appendBook(new Book("d"));
        Iterator it = shelf.iterator();
        while (it.hasNext()) {
            Book book = (Book)it.next();
            System.out.println(book.getName());
        }
    }
}

 

迭代器模式

标签:end   etl   []   over   span   img   als   gre   技术分享   

原文地址:http://www.cnblogs.com/panning/p/6680291.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!