Wednesday, February 06, 2008

* Patterns : Iterator Behavioral Pattern

Iterator Behavioral Pattern provides an access interface to an aggregate or collection object for clients. The iterator abstracts the clients from how the collection has been structured and also provides sequential navigation capabilities over collection.

Consider the following class diagram :

Iterator

NodeCollection type holds objects of type Node and there are two Iterators provided for NodeCollection objects.

The client code looks like following :

public class Client
{
    NodeCollection nc = new NodeCollection();
    BaseIterator forwardIterator;
    public void Run()
    {
        nc.AddNode(new Node("Name 0"));
        nc.AddNode(new Node("Name 1"));
        nc.AddNode(new Node("Name 2"));
        nc.AddNode(new Node("Name 3"));
        nc.AddNode(new Node("Name 4"));
        nc.AddNode(new Node("Name 5"));
        nc.AddNode(new Node("Name 6"));
        nc.AddNode(new Node("Name 7"));

        forwardIterator = nc.GetForwardIterator();
        Node n = forwardIterator.FirstNode();
        Console.WriteLine(n.Name);
        n = forwardIterator.NextNode();
        Console.WriteLine(n.Name);
        n = forwardIterator.NextNode();
        Console.WriteLine(n.Name);
        n = forwardIterator.NextNode();
        Console.WriteLine(n.Name);
        n = forwardIterator.NextNode();
        Console.WriteLine(n.Name);
    }
}

 

If iterators are not provided, client needs to know how to access each element using [index]. But with iterators the accessing code becomes much simpler & can be same for any type of collection structures.

Download Iterator Behavioral Pattern Source Code

Other Design Patterns

No comments:

Post a Comment