1. 程式人生 > >設計模式(10)叠代器模式

設計模式(10)叠代器模式

ali 它的 alt set override getname () mov 價格

叠代器模式提供了一種方法順序訪問一個聚合對象中的各個元素,而又不暴露其內部的表示。

技術分享圖片

下面我們利用java自帶的叠代器接口實現這個叠代器模式

首先我們定義一個自定義的集合類,並實現它的叠代器

public class Book {

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

    /**
     * 名稱
     */
    private String name;
    /**
     * 價格
     
*/ private Double price; public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } }
public class MyCollection {

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

    public void add(Book data) {
        dataList.add(data);
    }

    public void remove(Book data) {
        dataList.remove(data);
    }

    public MyIterator getIterator() {
        
return new MyIterator(this.dataList); } }
public class MyIterator implements Iterator<Book> {

    private List<Book> dataList;

    private int index;

    public MyIterator(List<Book> dataList) {
        this.dataList = dataList;
        index = 0;
    }

    @Override
    public boolean hasNext() {
        return index < dataList.size();
    }

    @Override
    public Book next() {
        return dataList.get(index++);
    }
}

測試

public static void main(String[] args) {
        MyCollection collection = new MyCollection();
        collection.add(new Book("SQL從刪庫到跑路",66.6));
        collection.add(new Book("JAVA從入門到放棄",88.8));

        MyIterator iterator = collection.getIterator();
        while (iterator.hasNext()) {
            Book book = iterator.next();
            System.out.println("書名:"+ book.getName() + ",售價:" + book.getPrice());
        }
    }

結果

技術分享圖片

設計模式(10)叠代器模式