0%

设计模式-迭代器模式

学习其实现方式

迭代器模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//Iterator迭代器抽象类
abstract class Iterator
{
public abstract object First();
public abstract object Next();
public abstract bool IsDone();
public abstract object CurrentItem();
}
//具体迭代器类
class ConcreateIterator : Iterator
{
private ConcreateAggregate aggregate;
private int current = 0;
public ConcreateIterator(ConcreateAggregate aggregate)
{
this.aggregate = aggregate;
}
public override object First()
{
return this.aggregate[0];
}
public override object Next()
{
object ret = null;
current++;
if(current < aggregate.Count)
{
ret = aggregate[current];
}
return ret;
}
public override bool IsDone()
{
return current >= aggregate.Count;
}
public override object CurrentItem()
{
return aggrate[current];
}

}
//抽象聚集类
abstract class Aggregate
{
public abstract Iterator CreateIterator();//创建迭代器
}
//具体聚集类
class ConcreateAggregate : Aggregate
{
private IList<object> items new List<object>();
public override Iterator CreateIterator()
{
return new ConcreateIterator(this);
}
public int Count
{get { return items.Count;}}
public object this[int index]
{
get{return items[index];}
set{items.Insert(index, value);}
}
}
//Client
ConcreateAggregate ca = new ConcreateAggregate();
ca[0] = "0";
ca[1] = "1";
ca[2] = "2";
Iterator i = new ConcreateIterator(ca);
object item = i.First();
while(!i.IsDone)
{
Console.WriteLine(i.CurrentItem());
i.Next();
}