1. 迭代器模式
提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示
A: 当你需要访问一个聚合对象,而且不管这些对象是什么都需要遍历的时候,你就应该考虑使用迭代器模式。你需要对聚集有多种方式遍历时,可以考虑用迭代器模式。为遍历不同的聚集结构提供如开始,下一个,是否结束,当前哪一项等统一接口。
2. 迭代器实现
class Program
{
static void Main(string[] args)
{
ConcreteAggregate a = new ConcreteAggregate();
a[0] = "大鸟";
a[1] = "小菜";
a[2] = "行李";
a[3] = "老外";
a[4] = "公交内部员工";
a[5] = "小偷";
Iterator i = new ConcreteIterator(a);
//Iterator i = new ConcreteIteratorDesc(a);
object item = i.First();
while (!i.IsDone())
{
Console.WriteLine("{0} 请买车票!", i.CurrentItem());
i.Next();
}
Console.Read();
}
}
abstract class Aggregate
{
public abstract Iterator CreateIterator();
}
class ConcreteAggregate : Aggregate
{
private IList<object> items = new List<object>();
public override Iterator CreateIterator()
{
return new ConcreteIterator(this);
}
public int Count
{
get { return items.Count; }
}
public object this[int index]
{
get { return items[index]; }
set { items.Insert(index, value); }
}
}
abstract class Iterator
{
public abstract object First();
public abstract object Next();
public abstract bool IsDone();
public abstract object CurrentItem();
}
class ConcreteIterator : Iterator
{
private ConcreteAggregate aggregate;
private int current = 0;
public ConcreteIterator(ConcreteAggregate aggregate)
{
this.aggregate = aggregate;
}
public override object First()
{
return aggregate[0];
}
public override object Next()
{
object ret = null;
current++;
if (current < aggregate.Count)
{
ret = aggregate[current];
}
return ret;
}
public override object CurrentItem()
{
return aggregate[current];
}
public override bool IsDone()
{
return current >= aggregate.Count ? true : false;
}
}
class ConcreteIteratorDesc : Iterator
{
private ConcreteAggregate aggregate;
private int current = 0;
public ConcreteIteratorDesc(ConcreteAggregate aggregate)
{
this.aggregate = aggregate;
current = aggregate.Count - 1;
}
public override object First()
{
return aggregate[aggregate.Count - 1];
}
public override object Next()
{
object ret = null;
current--;
if (current >= 0)
{
ret = aggregate[current];
}
return ret;
}
public override object CurrentItem()
{
return aggregate[current];
}
public override bool IsDone()
{
return current < 0 ? true : false;
}
}
3. .NET的迭代器实现
class Program
{
static void Main(string[] args)
{
IList<string> a = new List<string>();
a.Add("大鸟");
a.Add("小菜");
a.Add("行李");
a.Add("老外");
a.Add("公交内部员工");
a.Add("小偷");
foreach (string item in a)
{
Console.WriteLine("{0} 请买车票!", item);
}
IEnumerator<string> e = a.GetEnumerator();
while (e.MoveNext())
{
Console.WriteLine("{0} 请买车票!", e.Current);
}
Console.Read();
}
}
A: 迭代器模式就是分离了集合对象的遍历行为,抽出一个迭代器类来负责,这样即可以做到不暴露集合的内部结构,又可以让外部代码透明地访问集合内部的数据。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。