forked from WeihanLi/DesignPatterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIterator.cs
More file actions
60 lines (45 loc) · 1.54 KB
/
Iterator.cs
File metadata and controls
60 lines (45 loc) · 1.54 KB
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
namespace IteratorPattern
{
internal abstract class Iterator
{
public abstract object First();
public abstract object Next();
public abstract bool IsDone();
public abstract object CurrentItem();
}
internal class ConcreteIterator : Iterator
{
private readonly ConcreteAggregate _aggregate;
private int _current = 0;
public ConcreteIterator(ConcreteAggregate aggregate) => _aggregate = aggregate;
public override object First()
{
return _aggregate[0];
}
public override object Next()
{
_current++;
return _current >= _aggregate.TotalCount ? null : _aggregate[_current];
}
public override bool IsDone() => _current >= _aggregate.TotalCount;
public override object CurrentItem() => _aggregate[_current];
}
internal class ConcreteIteratorDesc : Iterator
{
private readonly ConcreteAggregate _aggregate;
private int _current;
public ConcreteIteratorDesc(ConcreteAggregate aggregate)
{
_aggregate = aggregate;
_current = _aggregate.TotalCount - 1;
}
public override object First() => _aggregate[_aggregate.TotalCount - 1];
public override object Next()
{
_current--;
return _current >= 0 ? _aggregate[_current] : null;
}
public override bool IsDone() => _current < 0;
public override object CurrentItem() => _aggregate[_current];
}
}