1、迭代器 Iterator模式 一个一个遍历 行为型设计模式

1Iterator

iteratorcursorcontainer访

Iterator - iterator

使

1 int array[] = new int[3];    
2 for (int i = 0; i < array.length; i++) {
3     System.out.println(array[i]);
4 }

ArrayList

1 List<String> list = new ArrayList<String>();
2       for(int i = 0 ; i < list.size() ; i++){
3           String string = list.get(i);
4 }

iiterator

Iteratoriterate

2

(Book)(BookShelf),.

:

Aggregate: 
Iterator: 
BookShelf: 
BookShelfIterator: 
Book: 

2.1 Aggregate

package cn.design.iterator;

/**
* @author lin
* @version 1.0
* @date 2020-07-13 14:16
* @Description 表示集合的接口
*/
public interface Aggregate {
   /**
    * 在Aggregate接口中声明的方法只有一个一-iterator 方法。该方法会生成-一个用于遍历集合的迭代器。
    * 想要遍历集合中的元素时,可以调用iterator方法来生成一一个实现了Iterator接口的类的实例。
    */
   public abstract Iterator iterator();
}

2.2 Iterator

package cn.design.iterator;

/**
* @author lin
* @version 1.0
* @date 2020-07-13 14:30
* @Description TODO
*/
public interface Iterator {

   /**
    * 判断是否存在下一-个元素
    * 当集合中存在下一个元素
    * 时,该方法返回true;当集合中不存在下一个元素,即已经遍历至集合末尾时,该方法返回
    * false。hasNext 方法主要用于循环终止条件。
    *
    * @return
    */
   public abstract boolean hasNext();

   /**
    * 取下一个元素
    * 该方法返回的是集合
    * 中的一一个元素。但是,next方法的作用并非仅仅如此。为了能够在下次调用next方法时正确地返
    * 回下一个元素,该方法中还隐含着将迭代器移动至下一个元素的处理。说“隐含”,是因为
    * Iterator接口只知道方法名。想要知道next方法中到底进行了什么样的处理,还需要看一下实
    * 现了Iterator接口的类( BookShelfIterator)。这样,我们才能看懂next方法的作用。
    *
    * @return object
    */
   public abstract Object next();
}

2.3 Book

package cn.design.iterator;

/**
* @author lin
* @version 1.0
* @date 2020-07-13 14:33
* @Description TODO
*/
public class Book {
   private String name;

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

   public Book() {
  }

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

   public String getName() {
       return name;
  }

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

2.4 BookShelf

package cn.design.iterator;

/**
* @author lin
* @version 1.0
* @date 2020-07-13 19:00
* @Description TODO
*/
public class BookShelf implements Aggregate {
   /**
    * 这个书架中定义了books字段,它是Book类型的数组。该数组的大小( maxsize )在生成
    * BookShelf的实例时就被指定了。之所以将books字段的可见性设置为private,是为了防止.
    * 外部不小心改变了该字段的值。
    */
   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;
  }

   /**
    * BookShelf类对应的Iterator。当外部想要遍历书架时,就会调用这个方法。
    *
    * @return Iterator 实现类
    */
   @Override
   public Iterator iterator() {
       return new BookShelfIterator(this);
  }
}

 

2.5 BookShelfIterator

package cn.design.iterator;

/**
* @author lin
* @version 1.0
* @date 2020-07-13 19:03
* @Description TODO
*/
public class BookShelfIterator implements Iterator {
   /**
    * bookShelf字段表示BookShelfIterator所要遍历的书架。
    */
   private BookShelf bookShelf;
   /**
    * index字段表示迭代器当前所指向的书的下标。
    */
   private int index;

   /**
    * @param bookShelf
    */

   /**
    * 构造函数会将接收到的BookShelf的实例保存在bookShelf字段中,并将index初始化为0。
    *
    * @param bookShelf
    */
   public BookShelfIterator(BookShelf bookShelf) {
       this.bookShelf = bookShelf;
       this.index = 0;
  }

   /**
    * hasNext方法是Iterator接口中所声明的方法。该方法将会判断书架中还有没有下一-本书, .
    * 如果有就返回true,如果没有就返回false。而要知道书架中有没有下一本书,可以通过比较
    * index和书架中书的总册数( bookShelf . getLength ()的返回值)来判断。
    *
    * @return
    */
   @Override
   public boolean hasNext() {
       return index < bookShelf.getLength();
  }

   /**
    * next方法会返回迭代器当前所指向的书( Book的实例),并让迭代器指向下一-本书。它也是
    * Iterator接口中所声明的方法。next方法稍微有些复杂,它首先取出book变量作为返回值,
    * 然后让index指向后面- -本书。
    * 如果与本章开头的for语句来对比,这里的“让index指向后面一-本书”的处理相当于其中
    * 的i++,它让循环变量指向下一个元素。
    *
    * @return
    */
   @Override
   public Object next() {
       Book bookAt = bookShelf.getBookAt(index);
       index++;
       return bookAt;
  }
}
View Code

2.6 TestMain

package cn.design.iterator;

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

/**
* @author lin
* @version 1.0
* @date 2020-07-13 19:05
* @Description TODO
*/
public class TestMain {

   public static void main(String[] args) {
       BookShelf bookShelf = new BookShelf(4);
       bookShelf.appendBook(new Book("环游世界80天"));
       bookShelf.appendBook(new Book("圣经"));
       bookShelf.appendBook(new Book("灰姑娘"));
       bookShelf.appendBook(new Book("阿拉丁神灯"));
       Iterator it = bookShelf.iterator();
       while (it.hasNext()) {
           Book book = (Book) it.next();
           System.out.println(book.toString());
      }

//       ArrayList<String> list = new ArrayList<>();
//       list.add("aaaa");
//       list.add("bbbb");
//       list.add("cccc");
//       list.add("dddd");
//       java.util.Iterator<String> it2 = list.iterator();
//       while (it2.hasNext()) {
//           System.out.println("it2.next() = " + it2.next());
//       }
  }
}
View Code

:

Book{name='80'}
Book{name=''}
Book{name=''}
Book{name=''}

bookShelf. iterator()itIteratorwhileit.hasNext()while it.next()

3Iterator

Iterator

1Iterator ()

( API)IteratorhasNextnexthasNext next

2Concretelterator ()

Iterator( API)BookShelfIteratorBookShelfbookShelfindex

3Aggregate ()

Iterator( API)( API)-访Aggregateiterator

4ConcreteAggregate ( )

Aggregate(API)IteratorConcretelteratorBookShelfiterator

4

4.1iterator

       while (it.hasNext()) {
           Book book = (Book) it.next();
           System.out.println(book.toString());
      }

使IteratorhasNextnextBookShelfwhileBookShelf

BookShelfjava.util. vector?BookShelfBookShelfiteratorIterator(IteratorhasNext next)使while

BookShelf便

iteratorBookShelfIteratorIterator(1-6)使IteratorBookShelfIterator

4.2

使ConcreteAggregateConcreteIterator使AggregateIterator

使使

4.3JavaArrayList

Itr

/**
    * An optimized version of AbstractList.Itr
    */
   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();
      }
  }
ArrayList内部:

   /**
    * Returns an iterator over the elements in this list in proper sequence.
    *
    * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
    *
    * @return an iterator over the elements in this list in proper sequence
    */
   public Iterator<E> iterator() {
       return new Itr();
  }

 

Iterator使boolean hasNext();E next();访

Java

https://gitee.com/naimaohome/talk_about_fage.git


                

 

圈~

 

 注公众号

posted @ 2020-07-21 09:56  发哥讲Java  阅读(276)  评论(0编辑  收藏  举报