1// Iterator 2 3// Intent: "Provide a way to access the elements of an aggregate object 4// sequentially without exposing its underlying representation". 5 6// For further information, read "Design Patterns", p257, Gamma et al., 7// Addison-Wesley, ISBN:0-201-63361-2 8 9/**//* Notes: 10 * Here wish wish to separate node traversal from the nodes themselves. 11 * STL in ISO C++ is a highly successful application of this pattern. 12 * Generic programming is a great way to implement iterators. As this is 13 * not yet in C#, we use inheritance. 14 * 15*/ 16 17namespace Iterator_DesignPattern 18{ 19using System; 20using System.Collections; 21 22class Node 23{ 24privatestring name; 25publicstring Name 26{ 27get 28{ 29return name; 30 } 31 } 32public Node(string s) 33{ 34 name = s; 35 } 36 } 37 38class NodeCollection 39{ 40private ArrayList list =new ArrayList(); 41privateint nodeMax =0; 42 43// left as a student exercise - implement collection 44// functions to remove and edit entries also 45publicvoid AddNode(Node n) 46{ 47 list.Add(n); 48 nodeMax++; 49 } 50public Node GetNode(int i) 51{ 52return ((Node) list[i]); 53 } 54 55publicint NodeMax 56{ 57get 58{ 59return nodeMax; 60 } 61 } 62 } 63 64/**//* 65 * The iterator needs to understand how to traverse the collection 66 * It can do that as way it pleases - forward, reverse, depth-first, 67*/ 68abstractclass Iterator 69{ 70abstractpublic Node Next(); 71 } 72 73class ReverseIterator : Iterator 74{ 75private NodeCollection nodeCollection; 76privateint currentIndex; 77 78public ReverseIterator (NodeCollection c) 79{ 80 nodeCollection = c; 81 currentIndex = c.NodeMax -1; // array index starts at 0! 82 } 83 84// note: as the code stands, if the collection changes, 85// the iterator needs to be restarted 86overridepublic Node Next() 87{ 88if (currentIndex ==-1) 89returnnull; 90else 91return(nodeCollection.GetNode(currentIndex--)); 92 } 93 } 94 95/**////<summary> 96/// Summary description for Client. 97///</summary> 98publicclass Client 99{ 100publicstaticint Main(string[] args) 101{ 102 NodeCollection c =new NodeCollection(); 103 c.AddNode(new Node("first")); 104 c.AddNode(new Node("second")); 105 c.AddNode(new Node("third")); 106 107// now use iterator to traverse this 108 ReverseIterator i =new ReverseIterator(c); 109 110// the code below will work with any iterator type 111 Node n; 112do 113{ 114 n = i.Next(); 115if (n !=null) 116 Console.WriteLine("{0}", n.Name); 117 }while (n !=null); 118 119return0; 120 } 121 } 122} 123 124