Iterator Pattern (9)
设计模式原则:
类只有唯一的理由去改变。
迭代器模式:
提供一种访问顺序存放元素的一种访问方式,使得我们使用这些元素的时候无需知道其底层的具体实现。
示例代码:
using System;
using
System.Text;
using
System.IO;
namespace Hello
{
//Iterator Interface
public interface Iterator
{
bool HasNext();
object Next();
}
//DinerMenuIterator
public class DinerMenuIterator : Iterator
{
string[] items;
int position = 0;
public DinerMenuIterator(string[]
items)
{
this.items = items;
}
public object Next()
{
string menuItem = items[position];
position +=
1;
return menuItem;
}
public bool HasNext()
{
if (position > items.Length || items[position] == null)
{
return false;
}
else
{
return true;
}
}
}
//Diner Menu
public class DinerMenu
{
const int MAX_ITEMS =
6;
int numberOfItems = 0;
string[] MenuItems;
public DinerMenu()
{
MenuItems = new string[6];
}
public void AddItems(string item)
{
if (numberOfItems < MAX_ITEMS)
{
MenuItems[numberOfItems]
= item;
numberOfItems++;
}
}
public Iterator
CreateIterator()
{
return new DinerMenuIterator(MenuItems);
}
}
class Program
{
static void Main(string[] args)
{
DinerMenu dinerMenu = new
DinerMenu();
dinerMenu.AddItems("Sandwich");
dinerMenu.AddItems("Burger");
dinerMenu.AddItems("Coke");
dinerMenu.AddItems("Wine");
Iterator menuIterator =
dinerMenu.CreateIterator();
while (menuIterator.HasNext())
{
Console.WriteLine((string)menuIterator.Next());
}
}
}
}