一、什么是迭代器模式
通用的数据集合访问方式。
二、迭代器模式的作用
屏蔽不同集合的构造,提供一个通用的方法对数据集进行访问,就像foreach一样
三、迭代器模式的使用场景
这个.net已经实现的非常好了。。。直接用foreach就好。。
四、如何实现迭代器模式
主程序:
namespace Iterator
{
class Program
{
static void Main(string[] args)
{
{
MyList<DeviceModel> deviceModels = new MyList<DeviceModel>();
deviceModels.Add(new DeviceModel()
{
Code = 1,
Name = "设备1"
});
deviceModels.Add(new DeviceModel()
{
Code = 2,
Name = "设备2"
});
deviceModels.Add(new DeviceModel()
{
Code = 3,
Name = "设备3"
});
Iiterator<DeviceModel> iterator = deviceModels.GetIterator();
while (iterator.MoveNext())
{
DeviceModel device = iterator.Current;
Console.WriteLine("Code:{0},Name:{1}", device.Code, device.Name);
}
}
Console.WriteLine("***********************************************");
{
DeviceModel[] deviceModels = new DeviceModel[3];
deviceModels[0] = new DeviceModel()
{
Code = 1,
Name = "设备1"
};
deviceModels[1] = new DeviceModel()
{
Code = 2,
Name = "设备2"
};
deviceModels[2] = new DeviceModel()
{
Code = 3,
Name = "设备3"
};
MyArray<DeviceModel> myArray = new MyArray<DeviceModel>(deviceModels);
Iiterator<DeviceModel> iterator = myArray.GetIterator();
while (iterator.MoveNext())
{
DeviceModel device = iterator.Current;
Console.WriteLine("Code:{0},Name:{1}", device.Code, device.Name);
}
}
}
}
}
List迭代器:
//MyList.cs
namespace Iterator
{
public class MyList<T>
{
private List<T> _List = new List<T>();
public void Add(T model)
{
_List.Add(model);
}
public List<T> GetList()
{
return this._List;
}
public Iiterator<T> GetIterator()
{
return new MyListIterator<T>(this);
}
}
}
//MyListIterator.cs
namespace Iterator
{
public class MyListIterator<T> : Iiterator<T>
{
private List<T> _List = null;
public MyListIterator(MyList<T> myList)
{
this._List = myList.GetList();
}
private int _Index = -1;
public T Current
{
get
{
return this._List[_Index];
}
}
public bool MoveNext()
{
return this._List.Count > ++this._Index;
}
public void Reset()
{
this._Index = -1;
}
}
}
Array迭代器:
//MyArray.cs
namespace Iterator
{
public class MyArray<T>
{
private T[] _Array = null;
public MyArray(T[] array)
{
_Array = array;
}
public T[] GetArray()
{
return this._Array;
}
public Iiterator<T> GetIterator()
{
return new MyArrayIterator<T>(this);
}
}
}
//MyArrayIterator.cs
namespace Iterator
{
public class MyArrayIterator<T>: Iiterator<T>
{
private T[] _Array = null;
public MyArrayIterator(MyArray<T> myArray)
{
this._Array = myArray.GetArray();
}
private int _Index = -1;
public T Current
{
get
{
return this._Array[_Index];
}
}
public bool MoveNext()
{
return this._Array.Length > ++this._Index;
}
public void Reset()
{
this._Index = -1;
}
}
}
迭代器接口Iiterator.cs:
namespace Iterator
{
public interface Iiterator<T>
{
T Current { get; }
bool MoveNext();
void Reset();
}
}
DeviceModel.cs
namespace Iterator
{
public class DeviceModel
{
public int Code { get; set; }
public string Name { get; set; }
}
}
平时还是直接foreach完事。。。要是没有此类功能的话,倒是可以自己写一个。
以上为本章所有内容。
完。