1. 程式人生 > 實用技巧 >1、迭代器 Iterator模式 一個一個遍歷 行為型設計模式

1、迭代器 Iterator模式 一個一個遍歷 行為型設計模式

1Iterator

iteratorcursorcontainer

Iterator - iterator

使

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

ArrayList

1List<String>list=newArrayList<String>();
2for(inti=0;i<list.size();i++){
3Stringstring=list.get(i);
4}

iiterator

Iteratoriterate

2

(Book)(BookShelf),.

:

Aggregate:
Iterator:
BookShelf:
BookShelfIterator:
Book:

2.1 Aggregate

packagecn.design.iterator;

/**
*@authorlin
*@version1.0
*@date2020-07-1314:16
*@Description
*/
publicinterfaceAggregate{
/**
*Aggregate-iterator-
*調iteratorIterator
*/
publicabstractIteratoriterator();
}

2.2 Iterator

packagecn.design.iterator;

/**
*@authorlin
*@version1.0
*@date2020-07-1314:30
*@DescriptionTODO
*/
publicinterfaceIterator{

/**
*-
*
*true;
*falsehasNext
*
*@return
*/
publicabstractbooleanhasNext();

/**
*
*
*next調next
*
*Iteratornext
*Iterator(BookShelfIterator)next
*
*@returnobject
*/
publicabstractObjectnext();
}

2.3 Book

packagecn.design.iterator;

/**
*@authorlin
*@version1.0
*@date2020-07-1314:33
*@DescriptionTODO
*/
publicclassBook{
privateStringname;

publicBook(Stringname){
this.name=name;
}

publicBook(){
}

publicvoidsetName(Stringname){
this.name=name;
}

publicStringgetName(){
returnname;
}

@Override
publicStringtoString(){
return"Book{"+
"name='"+name+'\''+
'}';
}
}

2.4 BookShelf

packagecn.design.iterator;

/**
*@authorlin
*@version1.0
*@date2020-07-1319:00
*@DescriptionTODO
*/
publicclassBookShelfimplementsAggregate{
/**
*books,Book(maxsize)
*BookShelfbooksprivate,.
*
*/
privateBook[]books;
privateintlast=0;

publicBookShelf(intmaxSize){
this.books=newBook[maxSize];
}

publicBookgetBookAt(intindex){
returnbooks[index];
}

publicvoidappendBook(Bookbook){
this.books[last]=book;
last++;
}

publicintgetLength(){
returnlast;
}

/**
*BookShelfIterator調
*
*@returnIterator
*/
@Override
publicIteratoriterator(){
returnnewBookShelfIterator(this);
}
}

2.5 BookShelfIterator

packagecn.design.iterator;

/**
*@authorlin
*@version1.0
*@date2020-07-1319:03
*@DescriptionTODO
*/
publicclassBookShelfIteratorimplementsIterator{
/**
*bookShelfBookShelfIterator
*/
privateBookShelfbookShelf;
/**
*index
*/
privateintindex;

/**
*@parambookShelf
*/

/**
*BookShelfbookShelfindex0
*
*@parambookShelf
*/
publicBookShelfIterator(BookShelfbookShelf){
this.bookShelf=bookShelf;
this.index=0;
}

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

/**
*next(Book),-
*Iteratornextbook,
*index--
*forindex-
*i++,
*
*@return
*/
@Override
publicObjectnext(){
BookbookAt=bookShelf.getBookAt(index);
index++;
returnbookAt;
}
}

2.6 TestMain

packagecn.design.iterator;

importjava.util.AbstractCollection;
importjava.util.ArrayList;
importjava.util.List;

/**
*@authorlin
*@version1.0
*@date2020-07-1319:05
*@DescriptionTODO
*/
publicclassTestMain{

publicstaticvoidmain(String[]args){
BookShelfbookShelf=newBookShelf(4);
bookShelf.appendBook(newBook("80"));
bookShelf.appendBook(newBook(""));
bookShelf.appendBook(newBook(""));
bookShelf.appendBook(newBook(""));
Iteratorit=bookShelf.iterator();
while(it.hasNext()){
Bookbook=(Book)it.next();
System.out.println(book.toString());
}

//ArrayList<String>list=newArrayList<>();
//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()){
Bookbook=(Book)it.next();
System.out.println(book.toString());
}

使IteratorhasNextnext調BookShelfwhileBookShelf

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

BookShelf調便

iteratorBookShelfIteratorIterator(1-6)使IteratorBookShelfIterator

4.2

使ConcreteAggregateConcreteIterator使AggregateIterator

使使

4.3JavaArrayList

Itr

/**
*AnoptimizedversionofAbstractList.Itr
*/
privateclassItrimplementsIterator<E>{
intcursor;//indexofnextelementtoreturn
intlastRet=-1;//indexoflastelementreturned;-1ifnosuch
intexpectedModCount=modCount;

publicbooleanhasNext(){
returncursor!=size;
}

@SuppressWarnings("unchecked")
publicEnext(){
checkForComodification();
inti=cursor;
if(i>=size)
thrownewNoSuchElementException();
Object[]elementData=ArrayList.this.elementData;
if(i>=elementData.length)
thrownewConcurrentModificationException();
cursor=i+1;
return(E)elementData[lastRet=i];
}

publicvoidremove(){
if(lastRet<0)
thrownewIllegalStateException();
checkForComodification();

try{
ArrayList.this.remove(lastRet);
cursor=lastRet;
lastRet=-1;
expectedModCount=modCount;
}catch(IndexOutOfBoundsExceptionex){
thrownewConcurrentModificationException();
}
}

@Override
@SuppressWarnings("unchecked")
publicvoidforEachRemaining(Consumer<?superE>consumer){
Objects.requireNonNull(consumer);
finalintsize=ArrayList.this.size;
inti=cursor;
if(i>=size){
return;
}
finalObject[]elementData=ArrayList.this.elementData;
if(i>=elementData.length){
thrownewConcurrentModificationException();
}
while(i!=size&&modCount==expectedModCount){
consumer.accept((E)elementData[i++]);
}
//updateonceatendofiterationtoreduceheapwritetraffic
cursor=i;
lastRet=i-1;
checkForComodification();
}

finalvoidcheckForComodification(){
if(modCount!=expectedModCount)
thrownewConcurrentModificationException();
}
}

ArrayList

/**
*Returnsaniteratorovertheelementsinthislistinpropersequence.
*
*<p>Thereturnediteratoris<ahref="#fail-fast"><i>fail-fast</i></a>.
*
*@returnaniteratorovertheelementsinthislistinpropersequence
*/
publicIterator<E>iterator(){
returnnewItr();
}

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

Java

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


圈~

注公眾號