Iterator Design Pattern

There are some exceptions in the Design Patterns world when design patterns are explained pretty well. Iterator is one of such patterns. However, there is no surprise in that, since this pattern is very easy to use.

So, what is the purpose of this pattern? Basically, this is used when you want to have some custom collection that might have custom way of sequencing your elements. When you have such custom container, then you can use iterator design pattern.

How to implement this pattern? Well, it is very easy. First of all, you provide the implementation for Iterator:

interface Iterator<T> {
    bool HasNext();
    T Next();

Then, you implement some container that is able to return the iterator of elements specified:

class Container<T> {
    static Iterator<T> GetIterator() {
       return // Iterator<T> is instantiated as a new object

And that is it. It is both easy and simple design pattern. I do not think there is something more to tell about it.

When would you use it directly? Probably, never, since all modern languages have interfaces in place that already have Iterator implemented somehow (e.g. C# has IEnumerable). And these interfaces are being implemented in case you actually need custom way of sequencing your elements in the container.

Leave a Reply

Your email address will not be published. Required fields are marked *