Tuesday 4 August 2015

The Iterator Pattern

 The Iterator Pattern

Defined

The Iterator Pattern provides a way to access the elements of an aggregate sequentially without exposing its underlying representation.

Diagram




Code Example

Below is a code example of how to allow a client  to iterate through a collection,  without  caring about if the collection is an array or a list etc, and to do all of this without having to modify the client code, i.e if another collection type of an object presents itself, client code doesn't need changing. Open-closed principle ;)

 public interface IIterator
{
  bool HasNext();
  object Next();
}

public abstract class CatenatedStringInterator : IIterator
{
   protected string _theStringToIterateOver;
   protected int lastSubstringPoint = 0;
  
   public abstract bool HasNext();
   public abstract object Next();
  
}

public class CommaSeperatedStringInterator : CatenatedStringInterator
{
 

    public CommaSeperatedStringInterator(string theStringToIterateOver)
    {
       _theStringToIterateOver = theStringToIterateOver;
    }

     public override bool HasNext()
    {
       //Check if there is a next string by looking for commas
    }
   
    public override object Next()
    {
       //get next string
    }
}

public class AstrixSeperatedStringInterator : CatenatedStringInterator
{
    private string _theStringToIterateOver;
    private int lastSubstringPoint = 0;

    public AstrixSeperatedStringInterator(string theStringToIterateOver)
    {
       _theStringToIterateOver = theStringToIterateOver;
    }

     public override  bool HasNext()
    {
       //Check if there is a next string by looking for Astrixes
    }
   
    public override object Next()
    {
       //get next string
    }
}

public class CatenatedStringPrinter
{
     public void PrintStringsInFile(IIterator iterator)
      {
   
       if (iterator.HasNext())
      {
          System.Print((String)iterator.Next());
       }
   }
}


Bullet Points 

  •  An iterator allows access to an aggregates elements without exposing its internal structure.
  • An Iterator takes the job of iterating over an aggregate an encapsulates it in another object.
  • When using an Iterator, we relieve the aggregate of the responsibility of supporting operations for traversing its data.
  • An Iterator provides a common interface for traversing the items of an aggregate, allowing you to use polymorphism when writing code that makes use of the items of the aggregate.
  • We should strive to assign only one responsibility to each class.

No comments:

Post a Comment