迭代模式

Iterator
行为模式
它把对容器中包含的内部对象的访问委让给外部类,使用Iterator(遍历)按顺序进行遍历访问的设计模式。

角色和职责:
Iterator(迭代器接口):该接口必须实现迭代功能的最小定义方法集,比如提供hashNext(),next()方法
ConcreteIterator(迭代器实现类):迭代器接口Iterator的实现类。可以根据具体情况加以实现,需要得到内部信息,所以作为内部类
Aggregate(容器接口):定义基本功能以及提供类似Iterator()的方法。
concreteAggregate(容器实现类):容器接口的实现类。必须实现Iterator()方法。

优点:
1.实现功能分离,简化容器接口。让容器只实现本身的基本功能,把迭代功能委让给外部类实现,复合类的设计原则。
2.隐藏容器的实现细节。
3.为容器或其子容器提供了一个统一接口,一方面方便调用;另一方面使得调用者不必关注迭代器的实现细节。
4.可以为容器或其子容器实现不同的迭代方法或多个迭代方法。

在这里插入图片描述

//pojo
public class Book {
    private String ISBN;
    private String name;
    private double price;

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

    @Override
    public String toString() {
        return "Book{" +
                "ISBN='" + ISBN + '\'' +
                ", name='" + name + '\'' +
                ", price=" + price +
                '}';
    }

    public String getISBN() {
        return ISBN;
    }

    public void setISBN(String ISBN) {
        this.ISBN = ISBN;
    }

    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;
    }
}


//concreteAggregate(容器实现类)
public class BookList {
    private List<Book> bookList;
    private int index;//遍历到哪一个
    private Iterator iterator;

    public BookList(){
        bookList = new ArrayList<>();
    }

    //添加书籍
    public void addBook(Book book){
        bookList.add(book);
    }

    //删除书籍
    public void deleteBook(Book book){
        int bookIndex = bookList.indexOf(book);//找到相关对象的索引
        bookList.remove(bookIndex);
    }

   /* //判断是否有下一本书
    public boolean hashNext(){
        if(index >= bookList.size()){
            return false;
        }
        return true;
    }

    //获得下一本书
    public Book getNext(){
        return bookList.get(index++);
    }*/

   public Iterator iterator(){
       return new Itr();
   }

   private class Itr implements Iterator{
       @Override
       public boolean hasNext() {
           if(index >= bookList.size()){
               return false;
           }
           return true;
       }

       @Override
       public Object next() {
           return bookList.get(index++);
       }

       @Override
       public void remove() {
       }
       @Override
       public void forEachRemaining(Consumer action) {
       }
   }

}


public class MainClass {
    public static void main(String[] args) {
        BookList bookList = new BookList();
        Book book1 = new Book("1","Java编程",90);
        Book book2 = new Book("2","Java思想",90);
        Book book3 = new Book("3","Java入门到放弃",90);

        bookList.addBook(book1);
        bookList.addBook(book2);
        bookList.addBook(book3);

        /*while(bookList.hashNext()){
            System.out.println(bookList.getNext());
        }*/
        Iterator iterator = bookList.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }

    }
}

我们可以看下ArrayList的Iteraotr实现

private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

        public boolean hasNext() {
            return cursor != size;
        }

        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        @Override
        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> consumer) {
            Objects.requireNonNull(consumer);
            final int size = ArrayList.this.size;
            int i = cursor;
            if (i >= size) {
                return;
            }
            final Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length) {
                throw new ConcurrentModificationException();
            }
            while (i != size && modCount == expectedModCount) {
                consumer.accept((E) elementData[i++]);
            }
            // update once at end of iteration to reduce heap write traffic
            cursor = i;
            lastRet = i - 1;
            checkForComodification();
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值