有很多方法可以把對象堆起來成為一個集合
迭代器模式定義:提供一個方法順序訪問一個聚合對象中的各個元素
迭代器類圖:
現在引用《Head First》原文來說明迭代器模式的用法
原本兩家餐廳都是有自己的菜單實現方法
統一的迭代器接口:
public interface Iterator<T>
{
//判斷是否有下一個
bool hasNext();
//取得下一個菜單項
T next();
}
這裡用了泛型接口
我們知道list<>和數組在做遍歷操作的時候方法是不同的
public class DinerMenuIterator<T> : Iterator<BLL
{
MenuItem[] items;
int position =
//判斷是否有下一個
public bool hasNext()
{
if (position >= items
{
return false;
}
else
{
return true;
}
}
//取得下一個菜單項
public MenuItem next()
{
MenuItem menuItem = items[position];
position +=
return menuItem;
}
public DinerMenuIterator(MenuItem[] items)
{
ems = items;
}
}
public class PancakeHouseMenuIterator<T> : Iterator<BLL
{
List<MenuItem > items;
int position =
//判斷是否有下一個
public bool hasNext()
{
if (position >= items
{
return false;
}
else
{
return true;
}
}
//取得下一個菜單項
public MenuItem next()
{
MenuItem menuItem = items[position];
position +=
return menuItem;
}
public PancakeHouseMenuIterator(List<MenuItem> items)
{
ems = items;
}
}
public class DinerMenu
{
MenuItem[] menuItems;
public DinerMenu()
{
//菜單中最多放
menuItems = new MenuItem[
addItem(
}
/**//// <summary>
/// 增加菜單項
/// </summary>
/// <param name=
public void addItem(string name)
{
MenuItem _menuItem = new MenuItem(name);
//為了簡化代碼在這就加入一個菜單項
menuItems[
}
public Iterator<MenuItem> createIterator()
{
return new DinerMenuIterator<MenuItem >(menuItems );
}
}
public class PancakeHouseMenu
{
List<MenuItem > _menuItems;
public PancakeHouseMenu()
{
addItem(
}
/**//// <summary>
/// 增加菜單項
/// </summary>
/// <param name=
public void addItem(string name)
{
MenuItem _menuItem = new MenuItem(name);
_menuItems = new List<MenuItem>();
_menuItems
}
public Iterator<MenuItem> createIterator()
{
return new PancakeHouseMenuIterator<MenuItem>(_menuItems);
}
}
public class MenuItem
{
//菜單具體內容名稱
string _name;
public MenuItem(string name)
{
this
}
/**//// <summary>
/// 菜單項名稱
/// </summary>
public string name
{
get { return this
set { this
}
}
public class Waitress
{
PancakeHouseMenu _PancakeHouseMenu;
DinerMenu _DinerMenu;
public Waitress(PancakeHouseMenu pancakeHouseMenu
{
this
this
}
/**//// <summary>
/// 返回菜單項的內容
/// </summary>
/// <param name=
/// <returns></returns>
public string printMenu(Iterator<MenuItem> iterator)
{
string sContent =
while (iterator
{
MenuItem menuItem = (MenuItem)iterator
sContent += menuItem
}
return sContent;
}
public string printMenu()
{
//對象村餐廳菜單內容
Iterator<MenuItem > dinerMenuIterator = _DinerMenu
//對象村煎餅店餐廳菜單內容
Iterator<MenuItem> pancakeHouseMenuIterator = _PancakeHouseMenu
string s =
s +=
s +=
return s;
}
}
PancakeHouseMenu pancakeHouseMenu = new PancakeHouseMenu();
DinerMenu dinerMenu = new DinerMenu();
Waitress waitress = new Waitress(pancakeHouseMenu
string s = waitress
this
總結
From:http://tw.wingwit.com/Article/program/net/201311/13305.html