1 using System;
2 using System.Collections;
3
4 class Node
5 {
6 private string name;
7 public string Name
8 {
9 get
10 {
11 return name;
12 }
13 }
14 public Node(string s)
15 {
16 name = s;
17 }
18 }
19
20 class NodeCollection
21 {
22 private ArrayList list = new ArrayList();
23 private int nodeMax = 0;
24
25 // left as a student exercise - implement collection
26 // functions to remove and edit entries also
27 public void AddNode(Node n)
28 {
29 list.Add(n);
30 nodeMax++;
31 }
32 public Node GetNode(int i)
33 {
34 return ((Node) list[i]);
35 }
36
37 public int NodeMax
38 {
39 get
40 {
41 return nodeMax;
42 }
43 }
44 }
45
46 /*
47 * The iterator needs to understand how to traverse the collection
48 * It can do that as way it pleases - forward, reverse, depth-first,
49 */
50 abstract class Iterator
51 {
52 abstract public Node Next();
53 }
54
55 class ReverseIterator : Iterator
56 {
57 private NodeCollection nodeCollection;
58 private int currentIndex;
59
60 public ReverseIterator (NodeCollection c)
61 {
62 nodeCollection = c;
63 currentIndex = c.NodeMax -1; // array index starts at 0!
64 }
65
66 // note: as the code stands, if the collection changes,
67 // the iterator needs to be restarted
68 override public Node Next()
69 {
70 if (currentIndex == -1)
71 return null;
72 else
73 return(nodeCollection.GetNode(currentIndex--));
74 }
75 }
76
77 /// <summary>
78 /// Summary description for Client.
79 /// </summary>
80 public class Client
81 {
82 public static int Main(string[] args)
83 {
84 NodeCollection c = new NodeCollection();
85 c.AddNode(new Node("first"));
86 c.AddNode(new Node("second"));
87 c.AddNode(new Node("third"));
88
89 // now use iterator to traverse this
90 ReverseIterator i = new ReverseIterator(c);
91
92 // the code below will work with any iterator type
93 Node n;
94 do
95 {
96 n = i.Next();
97 if (n != null)
98 Console.WriteLine("{0}", n.Name);
99 } while (n != null);
100
101 return 0;
102 }
103 }