[Specical] Design Pattern - Behavioral Patterns - Iterator Pattern

50 篇文章 0 订阅
37 篇文章 0 订阅

2007

Section 4, Chapter 3


Iterator Pattern


Concept

Iterators allow sequential access of elements in a collection of objects without exposing its underlying code.


Use

If you have a list object and you wish to move through each element in the list sequentially and maintain your current place in the list, an iterator seems appropriate.


Design

  • Aggregate: a collection or aggregate object of some type whose elements we wish to iterate through.
  • Iterator: a tool to move through the aggregate elements and keep track of the progress.




Illustration




class List
{
  private ArrayList _listItems = new ArrayList();

  public Iterator CreateIterator()
  {
    return new Iterator(this);
  }
  
  public int Count
  {
    get{ return _listItems.Count; }
  }

  public void Append(object item)
  {
    _listItems.Add(item);
  }
  
  public void Remove(object item)
  {
    _listItems.Remove(item);
  }

  public void RemoveAt(int index)
  {
    _listItems.RemoveAt(index);
  }

  public object this[int index]
  {
    get{ return _listItems[index]; }
    set{ _listItems[index] = value; }
  }
}

class Iterator
{
  private List _collection;
  private int _currentIndex = 0;
  private int _stepCount = 1;

  public Iterator(List collection)
  {
    this._collection = collection;
  }

  public int Step
  {
    get{ return _stepCount; }
    set{ _stepCount = value; }
  }

  public object First()
  {
    _currentIndex = 0;
    return _collection[_currentIndex];
  }
  
  public object Next()
  {
    _currentIndex += _stepCount;
    if(!IsDone())
      return _collection[_currentIndex];
    else
      return null;
  }
  
  public object Last()
  {
    _currentIndex = _collection.Count - 1;
    return _collection[_currentIndex];
  }

  public object Current()
  {
    return _collection[_currentIndex];
  }

  public bool IsDone()
  {
    return _currentIndex >= _collection.Count ? true : false ;
  }
}


Iterator skipIterator = list.CreateIterator();
skipIterator.Step = 3;


for(object item = skipIterator.First(); !skipIterator.IsDone(); item = skipIterator.Next())


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值