IIterator
using System;
using System.Collections.Generic;
using System.Text;
namespace Pattern.Iterator
{
/**//// <summary>
/// 迭代器接口(IIterator)
/// </summary>
public interface IIterator
{
/**//// <summary>
/// 第一個對象
/// </summary>
/// <returns></returns>
MessageModel First();
/**//// <summary>
/// 下一個對象
/// </summary>
/// <returns></returns>
MessageModel Next();
/**//// <summary>
/// 當前對象
/// </summary>
MessageModel CurrentMessageModel { get; }
/**//// <summary>
/// 是否迭代完畢
/// </summary>
bool IsDone { get; }
}
}
Iterator
using System;
using System.Collections.Generic;
using System.Text;
namespace Pattern.Iterator
{
/**//// <summary>
/// 迭代器(Iterator)
/// </summary>
public class Iterator : IIterator
{
private Collection _collection;
private int _current = 0;
private int _step = 1;
/**//// <summary>
/// 構造函數
/// </summary>
/// <param name="collection"></param>
public Iterator(Collection collection)
{
this._collection = collection;
}
/**//// <summary>
/// 第一個對象
/// </summary>
/// <returns></returns>
public MessageModel First()
{
_current = 0;
return _collection[_current];
}
/**//// <summary>
/// 下一個對象
/// </summary>
/// <returns></returns>
public MessageModel Next()
{
_current += _step;
if (!IsDone)
{
return _collection[_current];
}
else
{
return null;
}
}
/**//// <summary>
/// 當前對象
/// </summary>
public MessageModel CurrentMessageModel
{
get { return _collection[_current]; }
}
/**//// <summary>
/// 是否迭代完畢
/// </summary>
public bool IsDone
{
get { return _current >= _collection.Count ? true : false; }
}
/**//// <summary>
/// 步長
/// </summary>
public int Step
{
get { return _step; }
set { _step = value; }
}
}
}