close

image

A. Iterator:

image

   1: interface Iterator
   2: {
   3:   object First();
   4:   object Next();
   5:   bool IsDone();
   6:   object CurrentItem();
   7: }

B. Iterable:

image

   1: namespace IteratorPatternConsole
   2: {
   3:     abstract class Iterable
   4:     {
   5:         public abstract Iterator CreateIterator();
   6:     }
   7: }
image

image

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:

image

Update ConcreteIterator:

We need to add an index operator [] to ConcreteIterable if we want to get the current item in collection of ConcreteIterable.

image

[] operator is added for ConcreteIterable.

image

For ConcreteIterator, we update CurrentItem(), First(), IsDone() and Next()

image

-------------------------------------------------------------------------------------

 

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: }

image

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 me1237guy 的頭像
    me1237guy

    天天向上

    me1237guy 發表在 痞客邦 留言(0) 人氣()