人人做人人澡人人爽欧美,国产主播一区二区,久久久精品五月天,羞羞视频在线观看免费

當前位置:蘿卜系統下載站 > 技術開發教程 > 詳細頁面

設計模式簡介(一)——Iterator

設計模式簡介(一)——Iterator

更新時間:2022-08-19 文章作者:未知 信息來源:網絡 閱讀次數:

[目的]
提供一種方法順序訪問一個聚合對象中各個元素, 而又不需暴露該對象的內部表示。

 [何時使用?]
訪問一個聚合對象的內容而無需暴露它的內部表示。支持對聚合對象的多種遍歷。為遍歷不同的聚合結構提供一個統一的接口(即, 支持多態迭代)。

[如何使用?]
Java風格的示例程序:

//抽象的集合
public interface Aggregate
{

public abstract Iterator iterator();
}

//抽象的Iterator
public interface Iterator
{

public abstract boolean hasNext();
public abstract Object next();
}

//具體的集合
public class ConcreteAggregate implements Aggregate
{

private Object[] collection;
private int last = 0;
public ConcreteAggregate()
{

collection = new Object[3];
}

public Object getItemAt(int index)
{

return collection[index];
}

public void appendItem(Object item)
{

this.collection[last] = item;
last++;
}

public int getLength()
{

return last;
}

public Iterator iterator()
{

//產生適合自己的Iterator
return new ConcreteIterator(this);
}
}

//具體的Iterator
public class ConcreteIterator implements Iterator
{

private ConcreteAggregate namecollection; //由它決定遍歷的集合類型
private int index;
public ConcreteIterator(ConcreteAggregate collection)
{

this.namecollection = collection;
this.index = 0;
}

public boolean hasNext()
{

if (index < namecollection.getLength())
{

return true;
}
else
{

return false;
}
}
public Object next()
{

//通過統一的getItemAt()接口實現對不同類型集合的遍歷
Object item = namecollection.getItemAt(index);
index++;
return item;
}
}

public class IteratorExample
{
public static void main(String[] args)
{
ConcreteAggregate collection = new ConcreteAggregate();
collection.appendItem(new Person("Davis"));
collection.appendItem(new Person("Frank"));
collection.appendItem(new Person("Jeny"));

//it的具體類型依賴于collection的類型而使用者并不需要關心這里面的區別

Iterator it = collection.iterator(); //返回適合collection的iterator
while (it.hasNext())
{
Person person = (Person)it.next();
System.out.println("" + person.getName());
}
}
}

這樣遍歷代碼保持了統一的風格,從而使使用者不必關心遍歷的對象到底是什么類型。


溫馨提示:喜歡本站的話,請收藏一下本站!

本類教程下載

系統下載排行

網站地圖xml | 網站地圖html
主站蜘蛛池模板: 白水县| 兴业县| 锦屏县| 南京市| 白水县| 永定县| 兴业县| 太和县| 齐河县| 晋城| 汉沽区| 健康| 台东县| 木兰县| 临漳县| 龙里县| 淮安市| 凌海市| 阿坝| 华容县| 元氏县| 湘潭市| 龙胜| 磐安县| 开平市| 红原县| 汾西县| 吕梁市| 禄劝| 浪卡子县| 连南| 焉耆| 调兵山市| 鄄城县| 黔西县| 淮阳县| 金门县| 东宁县| 姚安县| 桂平市| 无为县|