-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path迭代器模式.cs
136 lines (125 loc) · 3.58 KB
/
迭代器模式.cs
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
using System.Collections.Generic;
using Xunit;
namespace DesignMode
{
/// <summary>
/// 提供一种方法顺序访问一个聚合对象中各个元素
/// 而又不暴露该对象的内部表示
/// </summary>
public class 迭代器模式
{
[Fact]
public void Test()
{
//Net的迭代器
IList<string> list = new List<string>();
list.Add("小李");
list.Add("小红");
list.Add("小黑");
foreach (var b in list)
{
System.Console.WriteLine($"this is {b}");
}
//foreach in 做的工作其实是
IEnumerator<string> e = list.GetEnumerator();
while (e.MoveNext())
{
System.Console.WriteLine($"this is {e.Current}");
}
//GoF的迭代器
ConcreteAggregate a = new ConcreteAggregate();
a[0] = "小李";
a[1] = "小红";
a[2] = "小黑";
Iterator i = new ConcreteIterator(a);
object item = i.First();
System.Console.WriteLine($"this item is {item}");
while (!i.IsDone())
{
System.Console.WriteLine($"this is {i.CurrentItem()}");
i.Next();
}
System.Console.ReadLine();
}
/// <summary>
/// 迭代器抽象类
/// </summary>
abstract class Iterator
{
public abstract object First();
public abstract object Next();
public abstract bool IsDone();
public abstract object CurrentItem();
}
/// <summary>
/// 具体迭代器类
/// </summary>
class ConcreteIterator : Iterator
{
private ConcreteAggregate _aggregate;
private int current = 0;
public ConcreteIterator(ConcreteAggregate aggregate)
{
_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 bool IsDone()
{
return current > _aggregate.Count ? true : false;
}
public override object CurrentItem()
{
return _aggregate[current];
}
}
/// <summary>
/// 聚集抽象类
/// </summary>
abstract class Aggregate
{
public abstract Iterator CreateIterator();
}
/// <summary>
/// 具体聚集类
/// </summary>
class ConcreteAggregate : Aggregate
{
private List<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);
}
}
}
}
}