-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
78 lines (62 loc) · 1.78 KB
/
Program.cs
File metadata and controls
78 lines (62 loc) · 1.78 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
using System;
using System.Collections.Generic;
namespace Iterator;
public interface IIterator<T>
{
bool HasNext();
T Current { get; }
void MoveNext();
}
public interface IAggregate<T>
{
IIterator<T> CreateForwardIterator();
IIterator<T> CreateReverseIterator();
}
public class Playlist : IAggregate<string>
{
private readonly List<string> tracks = [];
public void AddTrack(string title) => tracks.Add(title);
public IIterator<string> CreateForwardIterator() => new PlaylistIterator(tracks, reverse: false);
public IIterator<string> CreateReverseIterator() => new PlaylistIterator(tracks, reverse: true);
}
public class PlaylistIterator(IList<string> items, bool reverse) : IIterator<string>
{
private int index = reverse ? items.Count : -1;
public bool HasNext() => reverse ? index > 0 : index < items.Count - 1;
public string Current => items[index];
public void MoveNext()
{
index += reverse ? -1 : 1;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("=== Iterator Pattern Demo ===");
Console.WriteLine();
var playlist = new Playlist();
playlist.AddTrack("Intro");
playlist.AddTrack("Verse");
playlist.AddTrack("Chorus");
playlist.AddTrack("Outro");
Console.WriteLine("Playing forward:");
var forward = playlist.CreateForwardIterator();
while (forward.HasNext())
{
forward.MoveNext();
Console.WriteLine($"-> {forward.Current}");
}
Console.WriteLine();
Console.WriteLine("Playing in reverse:");
var backward = playlist.CreateReverseIterator();
while (backward.HasNext())
{
backward.MoveNext();
Console.WriteLine($"<- {backward.Current}");
}
Console.WriteLine();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}