迭代器模式

1.定義#

提供一種方法訪問一個容器對象中各個元素,而又不需要暴露該對象的內(nèi)部細節(jié)。大部分語言中已經(jīng)在常用數(shù)據(jù)結(jié)構(gòu)類型中實現(xiàn),不需要自己動手實現(xiàn)。主要用于遍歷一個容器對象。實現(xiàn)中迭代器類主要用一個游標(biāo)在容器元素間前后移動。

2.類圖#

類圖

3.實現(xiàn)#

3.1抽象迭代器##

public interface Iterator{
  public Object next();
  public boolean hasNext();
  public boolean remove();
}

3.2具體迭代器##

public class ConcreteIterator implements Iterator {
  private ArrayList<T> arrayList = new ArrayList<T>();
  
  public int cursor = 0;
  public ConcreteIterator(ArryaList<T> _arrayList){
    this.arrayList = _arrayList;
  }

  public boolean hasNext(){
    if(this.cursor == this.arrayList.size())
    {
      return false;
    }else{
      return true;
    }
  }

  public Object next(){
    Object result = null;
    if(this.hasNext){
      result = this.arrayList.get(this.cursor++);
    }else{
      result = null;
    }
    return result;
  }

  public boolean remove(){
    this.arryaList.remove(this.cursor--);
  }
}

3.3抽象容器類##

public interface Aggregate{
  public void add(Object object);
  public void remove(Object object);
  public Iterator iterator();
}

3.4具體容器類##

public class ConcreteAggregate implements Aggregate{
  private ArrayList arrayList = new ArrayList();
  public void add(Object object){
    this.arrayList.add(object);
  }
  
  public Iterator iterator(){
    return new ConcreteIterator(this.arrayList);
  }
  public void remove(){}
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容