迭代器模式分析、结构图及基本代码
定义:提供一种方法顺序訪问一个聚合对象中的各个元素,而又不暴露该对象的内部表示。
适用地方:当须要訪问一个聚集对象。并且无论这些对象是什么都须要遍历的时候。就应该考虑用迭代器模式。或者当须要对聚集有多种方式遍历时,能够考虑使用迭代器模式。
虽然我们不须要显式地引用迭代器。但系统本身还是通过迭代器来实现遍历的。总的来说,迭代器模式就是分离了集合对象的遍历行为,抽象出一个迭代器类来负责,这样既能够做到不暴露集合的内部结构,又可让外部代码透明的訪问集合内部的数据。迭代器模式在訪问数组、集合、列表等数据时,尤其是数据库数据操作时。是很普遍的应用。
结构图:
基本代码:
using System;
using System.Collections.Generic;
using System.Text;
namespace 迭代器模式
{
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;
}
}
}