泛型迭代器模式

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
IDataObject<int> dataobject = new DataObject<int>();
dataobject.Add(1);
dataobject.Add(2);
Iterator<int> iterator = dataobject.GetInterator();
while (iterator.MoveNext())
{
Console.WriteLine(iterator.GetCurrent());
iterator.Next();
}
Console.ReadKey();
}
}
public interface Iterator<T>
{
bool MoveNext();
T GetCurrent();
void Next();
void Reset();
}
public class ConcreteIterator<T> : Iterator<T>
{
private IDataObject<T> _dataObject;
private int _index;
public ConcreteIterator(IDataObject<T> dataObject)
{
_dataObject = dataObject;
_index = 0;
}
public T GetCurrent()
{
return _dataObject.GetElement(_index);
}
public bool MoveNext()
{
if (_index < _dataObject.GetLength())
{
return true;
}
return false;
}
public void Next()
{
if (_index < _dataObject.GetLength())
{
_index++;
}
}
public void Reset()
{
_index = 0;
}
}
public interface IDataObject<T>
{
Iterator<T> GetInterator();
int GetLength();
T GetElement(int index);
void Add(T t);
void Remove(T t);
}
public class DataObject<T> : IDataObject<T>
{
List<T> _listT;
public DataObject()
{
_listT = new List<T>();
}
public T GetElement(int index)
{
return _listT[index];
}
public Iterator<T> GetInterator()
{
return new ConcreteIterator<T>(this);
}
public int GetLength()
{
return _listT.Count;
}
public void Add(T t) {
_listT.Add(t);
}
public void Remove(T t)
{
_listT.Remove(t);
}
}
}

posted @ 2019-03-21 15:52  东东东  阅读(69)  评论(0)    收藏  举报