首页 > 其他 > 详细

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

时间:2020-07-21 13:03:10      阅读:106      评论:0      收藏:0      [点我收藏+]

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 -
    * iteratorIterator
    */
   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;
    * falsehasNext 
    *
    * @return
    */
   public abstract boolean hasNext();

   /**
    * 
    * 
    * nextnext
    * 
    * Iteratornext
    * 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 )
    * BookShelfbooksprivate,.
    * 
    */
   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;
  }

   /**
    * BookShelfIterator
    *
    * @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 {
   /**
    * bookShelfBookShelfIterator
    */
   private BookShelf bookShelf;
   /**
    * index
    */
   private int index;

   /**
    * @param bookShelf
    */

   /**
    * BookShelfbookShelfindex0
    *
    * @param bookShelf
    */
   public BookShelfIterator(BookShelf bookShelf) {
       this.bookShelf = bookShelf;
       this.index = 0;
  }

   /**
    * hasNextIterator-, .
    * true,false
    * index( bookShelf . getLength ())
    *
    * @return
    */
   @Override
   public boolean hasNext() {
       return index < bookShelf.getLength();
  }

   /**
    * next( Book),-
    * Iteratornextbook,
    * index- -
    * forindex-
    * i++,
    *
    * @return
    */
   @Override
   public Object next() {
       Book bookAt = bookShelf.getBookAt(index);
       index++;
       return bookAt;
  }
}

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());
//       }
  }
}

:

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


技术分享图片                

 

圈~

 

 注公众号

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

原文:https://www.cnblogs.com/naimao/p/13353364.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!