Skip to content

Instantly share code, notes, and snippets.

@miteshsureja
Created June 11, 2017 07:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miteshsureja/7e1cad49c704a6b40c4510771a93b1ec to your computer and use it in GitHub Desktop.
Save miteshsureja/7e1cad49c704a6b40c4510771a93b1ec to your computer and use it in GitHub Desktop.
Iterator Design Pattern Example
using System;
using System.Collections;
using System.Collections.Generic;
namespace IteratorPattern
{
//Aggregate
public abstract class Aggregate
{
public abstract Iterator GetIterator();
}
}
using System;
using System.Collections;
using System.Collections.Generic;
namespace IteratorPattern
{
//ConcreteAggregate
public class MyObjectCollection : Aggregate
{
private ArrayList myList = new ArrayList();
public override Iterator GetIterator()
{
return new MyIterator(this);
}
public object this[int index]
{
get { return myList[index]; }
}
public int Count
{
get { return myList.Count; }
}
public void Add (object obj)
{
myList.Add(obj);
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
namespace IteratorPattern
{
//ConcreteIterator
public class MyIterator : Iterator
{
private MyObjectCollection aggregate;
int index;
public MyIterator(MyObjectCollection aggr)
{
this.aggregate = aggr;
index = 0;
}
public object CurrentItem()
{
return aggregate[index];
}
public object First()
{
return aggregate[0];
}
public bool IsDone()
{
return index >= aggregate.Count ;
}
public object Next()
{
object retVal = null;
if (index < aggregate.Count)
retVal = aggregate[index++];
return retVal;
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
namespace IteratorPattern
{
//Iterator
public interface Iterator
{
object First();
object Next();
object CurrentItem();
bool IsDone();
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IteratorPattern
{
class Program
{
//Client
static void Main(string[] args)
{
//MyCollection coll = new MyCollection();
//foreach(var item in coll)
// Console.WriteLine(item.ToString());
//Create myObject collection and items to it.
MyObjectCollection aggr = new MyObjectCollection();
aggr.Add(10);
aggr.Add(-20);
aggr.Add("Test");
aggr.Add(33);
aggr.Add("Iterator");
aggr.Add(52.6);
//Get Iterator and iterator all items
Iterator itor = aggr.GetIterator();
while (!itor.IsDone())
{
Console.WriteLine(itor.CurrentItem().ToString());
itor.Next();
}
Console.ReadLine();
}
}
}
@miteshsureja
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment