Skip to content

Instantly share code, notes, and snippets.

@ShirakawaYoshimaru
Created June 10, 2016 16:28
Show Gist options
  • Save ShirakawaYoshimaru/85b39ef3ce544ec85383ede57d835dc7 to your computer and use it in GitHub Desktop.
Save ShirakawaYoshimaru/85b39ef3ce544ec85383ede57d835dc7 to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
namespace Iterator3
{
public class BookShelf : Shelf<Book>
{
public Book GetRandom ()
{
int index = new System.Random ().Next (GetCount ());
return GetAt (index);
}
}
public class AnimeShelf : Shelf<DVD>
{
public DVD GetRandom ()
{
int index = new System.Random ().Next (GetCount ());
return GetAt (index);
}
}
public abstract class Shelf<T> : Aggeregate<T>
{
List<T> items = new List<T> ();
public T GetAt (int index)
{
return items [index];
}
public void Add (T data)
{
items.Add (data);
}
public void RemoveAt (int index)
{
items.RemoveAt (index);
}
public int GetCount ()
{
return items.Count;
}
public Iterator<T> Iterator ()
{
return new ShelfIterator<Shelf<T>,T> (this);
}
}
public class ShelfIterator<T1,T2> : Iterator<T2> where T1 : Shelf<T2>
{
private T1 shelf;
private int index;
public ShelfIterator (T1 shelf)
{
this.shelf = shelf;
}
public bool HasNext ()
{
return index < shelf.GetCount ();
}
public T2 Next ()
{
var item = shelf.GetAt (index);
index++;
return item;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment