定義標準遍歷操作契約:
using System;
using System.Collections.Generic;
using System.Text;
namespace Pattern.Iterator
{
///
/// 迭代器介面(IIterator)
///
public interface IIterator
{
///
/// 第一個物件
///
/// MessageModel
MessageModel First();
///
/// 下一個物件
///
/// MessageModel
MessageModel Next();
///
/// 當前物件
///
MessageModel CurrentMessageModel { get; }
///
/// 是否迭代完畢
///
bool IsDone { get; }
}
}
實作遍歷邏輯,支援步長控制:
using System;
using System.Collections.Generic;
using System.Text;
namespace Pattern.Iterator
{
///
/// 迭代器(Iterator)
///
public class Iterator : IIterator
{
private Collection _collection;
private int _current = 0;
private int _step = 1;
///
/// 建構函式
///
/// 集合
public Iterator(Collection collection)
{
this._collection = collection;
}
///
/// 第一個物件
///
/// MessageModel
public MessageModel First()
{
_current = 0;
return _collection[_current];
}
///
/// 下一個物件
///
/// MessageModel
public MessageModel Next()
{
_current += _step;
if (!IsDone)
{
return _collection[_current];
}
else
{
return null;
}
}
///
/// 當前物件
///
public MessageModel CurrentMessageModel
{
get { return _collection[_current]; }
}
///
/// 是否迭代完畢
///
public bool IsDone
{
get { return _current >= _collection.Count ? true : false; }
}
///
/// 步長
///
public int Step
{
get { return _step; }
set { _step = value; }
}
}
}
_current 追蹤當前位置,_step 控制移動步長。Collection 參考,透過索引器存取元素。IsDone 比較游標與 Count 判斷結束。Step 屬性支援跳躍式遍歷(如每隔 N 個元素)。| 模式角色 | 本例類別 | 說明 |
|---|---|---|
| Aggregate | ICollection | 抽象集合介面 |
| ConcreteAggregate | Collection | 具體集合,內部 List 管理元素 |
| Iterator | IIterator | 抽象迭代器介面 |
| ConcreteIterator | Iterator | 具體迭代器,游標遍歷邏輯 |