visit
The iterator design pattern helps solve this problem wherein a standard iterator will traverse different collection types.
public interface IVehicleIterator{
void First();
bool IsDone();
string Next();
string Current();
}
The car iterator is implemented over
List<string>
collection and provides an implementation of interface methods.public class CarIterator : IVehicleIterator
{
private List<string> _cars;
private int _current;
public CarIterator(List<string> cars)
{
_cars = cars;
_current = 0;
}
public string Current()
{
return _cars.ElementAt(_current);
}
public void First()
{
_current = 0;
}
public bool IsDone()
{
return _current >= _cars.Count;
}
public string Next()
{
return _cars.ElementAt(_current++);
}
}
The motorcycle iterator is implemented over
string[]
collection and provides an implementation of interface methods.public class MotercycleIterator : IVehicleIterator
{
private string[] _motercylces;
private int _current;
public MotercycleIterator(string[] motercylces)
{
_motercylces = motercylces;
_current = 0;
}
public string Current()
{
return _motercylces[_current];
}
public void First()
{
_current = 0;
}
public bool IsDone()
{
return _current >= _motercylces.Length;
}
public string Next()
{
return _motercylces[_current++];
}
}
public interface IVehicleAggregate{
IVehicleIterator CreateIterator();
}
public class Car : IVehicleAggregate
{
private List<string> _cars;
public Car()
{
_cars = new List<string> { "Car 1", "Car 2", "Car 3" };
}
public IVehicleIterator CreateIterator()
{
return new CarIterator(_cars);
}
}
public class Motercycle : IVehicleAggregate
{
private string[] _motercycles;
public Motercycle()
{
_motercycles = new[] { "Bike 1", "Bike 2", "Bike 3" };
}
public IVehicleIterator CreateIterator()
{
return new MotercycleIterator(_motercycles);
}
}
static void Main(string[] args)
{
IVehicleAggregate car = new Vehicles.Car();
IVehicleAggregate motercycle = new Vehicles.Motercycle();
IVehicleIterator carIterator = car.CreateIterator();
IVehicleIterator motercycleIterator = motercycle.CreateIterator();
PrintVehicles(carIterator);
PrintVehicles(motercycleIterator);
}
static void PrintVehicles(IVehicleIterator iterator)
{
iterator.First();
while (!iterator.IsDone())
{
Console.WriteLine(iterator.Next());
}
}
The PrintVehicles methods check if
!iterator.isDone
then output the collection element. No matter what collection we’re dealing with, implement methods like First, IsDone, and Next.Also published on .