1、迭代器 Iterator模式 一個一個遍歷 行為型設計模式
阿新 • • 發佈:2020-07-21
1、Iterator模式
迭代器(iterator)有時又稱遊標(cursor)是程序設計的軟件設計模式,可在容器(container,例如鏈表或者陣列)上遍訪的接口,設計人員無需關心容器的內容。
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}
將這裡的i的作用抽象化,通用化後形成的模式,在設計模式中稱為iterator模式。
Iterator模式用於在數據集合按照順序遍歷集合。英語單詞iterate有反復做某件事情的意思,漢語稱為“迭代器”。
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方法。該方法會生成-一個用於遍歷集合的迭代器。
*想要遍歷集合中的元素時,可以調用iter