在面向對象的軟件設計中,我們經常會遇到一類集合對象,這類集合對象的內部結構可能有著各種各樣的實現,但是歸結起來,無非有兩點是需要我們去關心的:一是集合內部的數據存儲結構,二是遍歷集合內部的數據。面向對象設計原則中有一條是類的單一職責原則,所以我們要盡可能的去分解這些職責,用不同的類去承擔不同的職責。Iterator模式就是分離了集合對象的遍歷行為,抽象出一個迭代器類來負責,這樣既可以做到不暴露集合的內部結構,又可讓外部代碼透明的訪問集合內部的數據。
提供一種方法順序訪問一個聚合對象中各個元素, 而又不需暴露該對象的內部表示。
一,結構:
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
二,示例代碼:
/**
* 抽象聚集
* @author Salmon
*
*/
public interface List {
public Iterator getIterator();
}
/**
* 抽象迭代器
* @author Salmon
*
*/
public interface Iterator {
public boolean moveNext();
public Object currentItem();
public void first();
public void next();
}
/**
* 具體聚集
* @author Salmon
*
*/
public class ConcreteList implements List {
int[] list;
public ConcreteList() {
list = new int[] { 1, 2, 3, 4, 5 };
}
public Iterator getIterator() {
return new ConcreteIterator(this);
}
public int getLength() {
return list.length;
}
public int getElement(int index) {
return list[index];
}
}
/**
* 具體迭代器
* @author Salmon
*
*/
public class ConcreteIterator implements Iterator {
private ConcreteList list;
private int index;
public ConcreteIterator(ConcreteList list) {
this.list = list;
index = 0;
}
public boolean moveNext() {
if (index < list.getLength())
return true;
else
return false;
}
public Object currentItem()
{
return list.getElement(index);
}
public void first() {
index = 0;
}
public void next() {
if (index < list.getLength()) {
index++;
}
}
}
/**
* 客戶端程序
* @author Salmon
*
*/
public class Program {
public static void main(String[] args) {
Iterator iterator;
List list = new ConcreteList();
iterator = list.getIterator();
while (iterator.moveNext()) {
Object o = iterator.currentItem();
System.out.println(o.toString());
iterator.next();
}
}
}
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

