close
A. Iterator:
1: interface Iterator
2: {
3: object First();
4: object Next();
5: bool IsDone();
6: object CurrentItem();
7: }
B. Iterable:
1: namespace IteratorPatternConsole
2: {
3: abstract class Iterable
4: {
5: public abstract Iterator CreateIterator();
6: }
7: }
C. ConcreteIterator:
1: class ConcreteIterator : Iterator
2: {
3: ConcreteIterable concreteIterable;
4: int current = 0;
5: public ConcreteIterator(ConcreteIterable concreteIterable)
6: {
7: this.concreteIterable = concreteIterable;
8: }
9: public object CurrentItem()
10: {
11: throw new NotImplementedException();
12: }
13:
14: public void First()
15: {
16: throw new NotImplementedException();
17: }
18:
19: public bool IsDone()
20: {
21: throw new NotImplementedException();
22: }
23:
24: public void Next()
25: {
26: throw new NotImplementedException();
27: }
28: }
D. ConcreteIterable:
1: class ConcreteIterable : Iterable
2: {
3: public override Iterator CreateIterator()
4: {
5: return new ConcreteIterator(this);
6: }
7: }
-------------------------------------------------------------------------------------
Update ConcreteIterable:
Update ConcreteIterator:
We need to add an index operator [] to ConcreteIterable if we want to get the current item in collection of ConcreteIterable.
[] operator is added for ConcreteIterable.
For ConcreteIterator, we update CurrentItem(), First(), IsDone() and Next()
-------------------------------------------------------------------------------------
Console portion:
1: static void Main(string[] args)
2: {
3: ConcreteIterable items = new ConcreteIterable();
4: items[0] = "pen";
5: items[1] = "erasor";
6: items[2] = "ruler";
7: items[3] = "pencil";
8: items[4] = "marker";
9:
10: Iterator i = new ConcreteIterator(items);
11: object item = i.First();
12: Console.WriteLine("Number of items = {0}", items.Count);
13: while(!i.IsDone())
14: {
15: Console.WriteLine("{0}", i.CurrentItem());
16: i.Next();
17: }
18: Console.ReadKey();
19: }
全站熱搜
留言列表