-
Notifications
You must be signed in to change notification settings - Fork 0
/
15Iterator.cs
120 lines (88 loc) · 3.96 KB
/
15Iterator.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
using System;
using System.Collections;
namespace DoFactory.GangOfFour.Iterator.Structural
{
class MainApp
{
static void Main()
{
FellowshipMembers members = new FellowshipMembers();
members[0] = "Frodo";
members[1] = "Gandalf";
members[2] = "Aragorn";
members[3] = "Legolas";
members[4] = "Merry";
members[5] = "Pippin";
members[6] = "Sam";
members[7] = "Gimli";
members[8] = "Boromir";
ConcreteIterator i = new ConcreteIterator(members);
Console.WriteLine("Members of the Fellowship of the ring:\n");
object item = i.First();
while (item != null)
{
Console.WriteLine(item);
item = i.Next();
}
Console.ReadKey();
}
}
abstract class Aggregate
{
public abstract Iterator CreateIterator();
}
class FellowshipMembers : Aggregate
{
private ArrayList _items = new ArrayList();
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 FellowshipMembers _aggregate;
private int _current = 0;
public ConcreteIterator(FellowshipMembers aggregate)
{
this._aggregate = aggregate;
}
public override object First()
{
return _aggregate[0];
}
public override object Next()
{
object ret = null;
if (_current < _aggregate.Count - 1)
{
ret = _aggregate[++_current];
}
return ret;
}
public override object CurrentItem()
{
return _aggregate[_current];
}
public override bool IsDone()
{
return _current >= _aggregate.Count;
}
}
}